【问题标题】:XElement namespaces (How to?)XElement 命名空间(如何?)
【发布时间】:2011-06-26 12:54:35
【问题描述】:

如何创建带有节点前缀的 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 exceptionTyp e)
在 System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
在 System.Xml.Linq.XNamespace.GetName(String localName)
在 System.Xml.Linq.XName.Get(字符串扩展名称)

【问题讨论】:

  • 查看XmlNamespaceManager 类。
  • 您的文档无效。它需要声明sphinx前缀。

标签: c# xml linq namespaces


【解决方案1】:

在 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>

【讨论】:

  • 谢谢,但对于第一个版本,我得到了 这不是我想要的;)))
  • @Edward83:见我的另一个例子。基本上你需要在某个地方的 xmlns 中指定命名空间...
  • 在我曾经做过的所有丑陋的黑客攻击之后(将命名空间附加到所有内容的递归静态方法)......我首先尝试了这种方法,但我没有在 XNamespace.Xmlns 前面加上前缀外部命名空间。为什么这个前缀甚至是必要的?是否将其设置为全局?
  • @micahhoover:您应该阅读 W3C 命名空间规范。我并不完全清楚你想要达到什么目标,或者出了什么问题。
【解决方案2】:

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

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

【讨论】:

  • 不错的方法(+1)!但是,在根 XML 元素具有多个 xmlns 属性的情况下,这对我不起作用,即:xmlns:soapenv="..." xmlns="..."。使用 xml.Root.GetDefaultNamespace() 确实得到了我想要的,这是普通 xmlns="..." 属性的值。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多