XElement 命名空间(如何?)

问题描述 投票:0回答:3

如何创建带有节点前缀的 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:“:”字符,十六进制值 ue 0x3A,不能包含在名称中。
在 System.Xml.XmlConvert.VerifyNCName(字符串名称,ExceptionType 异常Typ e)
在 System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
在 System.Xml.Linq.XNamespace.GetName(String localName)
在 System.Xml.Linq.XName.Get(字符串扩展名称)

c# xml linq namespaces
3个回答
124
投票

使用 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>

22
投票

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

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

-2
投票

逐步使用 LINQ to XML:

XNamespace ns = "http://url/for/sphinx";
XAttribute sphinx = new XAttribute(XNamespace.Xmlns + "sphinx", ns);
XElement docset = new XElement(ns + "docset", sphinx);               

XElement schema = new XElement(ns + "schema"); 
docset.Add(schema);

XElement field1 = new XElement(ns + "field", new XAttribute("name", "subject"));
XElement field2 = new XElement(ns +  "field", new XAttribute("name", "content"));
XElement attr = new XElement(ns + "attr",
    new XAttribute("name", "published"),
    new XAttribute("type", "timestamp"));

schema.Add(field1, field2, attr);  

Console.WriteLine(docset);

输出:

<sphinx:docset xmlns:sphinx="http://url/for/sphinx">
  <sphinx:schema>
    <sphinx:field name="subject" />
    <sphinx:field name="content" />
    <sphinx:attr name="published" type="timestamp" />
  </sphinx:schema>
</sphinx:docset>
© www.soinside.com 2019 - 2024. All rights reserved.