XElement 命名空间(如何?) [英] XElement namespaces (How to?)

查看:39
本文介绍了XElement 命名空间(如何?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建带有节点前缀的 xml 文档,例如:

How to create xml document with node prefix like:

<sphinx:docset>
  <sphinx:schema>
    <sphinx:field name="subject"/>
    <sphinx:field name="content"/>
    <sphinx:attr name="published" type="timestamp"/>
 </sphinx:schema>

当我尝试运行类似 new XElement("sphinx:docset") 之类的东西时,我得到了异常

When I try to run something like new XElement("sphinx:docset") i getting exception

未处理的异常:System.Xml.XmlException:':' 字符,十六进制值ue 0x3A,不能包含在名称中.
在 System.Xml.XmlConvert.VerifyNCName(String name, ExceptionType exceptionType)
在 System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
在 System.Xml.Linq.XNamespace.GetName(String localName)
在 System.Xml.Linq.XName.Get(String ExpandedName)

Unhandled Exception: System.Xml.XmlException: The ':' character, hexadecimal val ue 0x3A, cannot be included in a name.
at System.Xml.XmlConvert.VerifyNCName(String name, ExceptionType exceptionTyp e)
at System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
at System.Xml.Linq.XNamespace.GetName(String localName)
at System.Xml.Linq.XName.Get(String expandedName)

推荐答案

LINQ to XML 真的很简单:

It's really easy in LINQ to XML:

XNamespace ns = "sphinx";
XElement element = new XElement(ns + "docset");

或者使别名"正常工作以使其看起来像您的示例,如下所示:

Or to make the "alias" work properly to make it look like your examples, something like this:

XNamespace ns = "http://url/for/sphinx";
XElement element = new XElement("container",
    new XAttribute(XNamespace.Xmlns + "sphinx", ns),
    new XElement(ns + "docset",
        new XElement(ns + "schema"),
            new XElement(ns + "field", new XAttribute("name", "subject")),
            new XElement(ns + "field", new XAttribute("name", "content")),
            new XElement(ns + "attr", 
                         new XAttribute("name", "published"),
                         new XAttribute("type", "timestamp"))));

产生:

<container xmlns:sphinx="http://url/for/sphinx">
  <sphinx:docset>
    <sphinx:schema />
    <sphinx:field name="subject" />
    <sphinx:field name="content" />
    <sphinx:attr name="published" type="timestamp" />
  </sphinx:docset>
</container>

这篇关于XElement 命名空间(如何?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆