如何使用节点前缀创建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")我得到异常的东西时
new XElement("sphinx:docset")
未处理的异常:System.Xml.XmlException:名称中不能包含’:’字符,十六进制值0x3A。 在System.Xml.Linq.XName..ctor( XNamespace ns,String localName) 在System.Xml.Linq.XNamespace.GetName(String localName) 在System.Xml.Linq.XName..ctor(XNamespace ns,String localName).Xml.Linq.XName.Get(字符串expandName)
在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>