XElement命名空间(如何?)

如何创build具有节点前缀的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")我得到exception

未处理的exception:System.Xml.XmlException:名称中不能包含“:”字符(hex值0x3A)。 System.Xml.Xml.Linq.XName..ctor(XNamespace ns,String localName)在System.Xml.Linq.XNamespace.GetName(String localName)在System.Xml.XmlConvert.VerifyNCName(string名称,ExceptionType exceptionTyp e) .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> 

您可以阅读文档的命名空间,并在像这样的查询中使用它:

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