XElement命名空间(如何?)

时间:2011-02-13 18:24:46

标签: c# xml linq namespaces

如何使用节点前缀创建xml文档,如:

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

当我尝试运行类似new XElement("sphinx:docset")的内容时,我会遇到异常

  

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

2 个答案:

答案 0 :(得分:110)

LINQ to XML非常简单:

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

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

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>

答案 1 :(得分:20)

您可以阅读文档的命名空间并在以下查询中使用它:

XDocument xml = XDocument.Load(address);
XNamespace ns = xml.Root.Name.Namespace;
foreach (XElement el in xml.Descendants(ns + "whateverYourElementNameIs"))
    //do stuff