gpt4 book ai didi

c# - XElement namespace (如何?)

转载 作者:IT王子 更新时间:2023-10-29 03:42:09 26 4
gpt4 key购买 nike

如何创建带有节点前缀的 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") 之类的程序时,出现异常

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 中非常简单:

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>

关于c# - XElement namespace (如何?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com