命名空间的XElement(如何?) [英] XElement namespaces (How to?)
问题描述
如何创建XML文档的节点preFIX这样的:
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>
当我尝试运行像新的XElement(斯芬克斯:docset的)
我越来越例外
When I try to run something like new XElement("sphinx:docset")
i getting exception
未处理的异常信息:System.Xml.XmlException:在':'字符,十六进制VAL
UE 0x3A,不能被包含在一个名称。
在System.Xml.XmlConvert.VerifyNCName(字符串名称,ExceptionType exceptionTyp
E)
在System.Xml.Linq.XName..ctor(NS的XNamespace,字符串的localName)
在System.Xml.Linq.XNamespace.GetName(字符串的localName)
在System.Xml.Linq.XName.Get(字符串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真的很容易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屋!