的XElement命名空间(如何?)

问题描述:

如何使用节点前缀创建XML文档,如:的XElement命名空间(如何?)

<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:名称中不能包含':'字符,十六进制数字为0x3A。 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) 在System.Xml.Linq.XName.Get(字符串expandedName)

谢谢大家帮忙!;)

+0

查看`XmlNamespaceManager`类。 – 2011-02-13 18:29:59

+2

您的文件将无效。它需要声明`sphinx`前缀。 – 2011-02-13 18:54:04

这真的很容易在LINQ to XML:

XNamespace ns = "sphinx"; 
XElement element = new XElement(ns + "docset"); 

或者做t他的“别名”正常工作,以使它看起来像你的例子,这样的事情:

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> 
+0

谢谢,但对于第一个版本,我得到了这不是我想要的;))) – Edward83 2011-02-13 18:37:24

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

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