2011-02-13 68 views
63

如何使用節點前綴創建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

回答

98

這真的很容易在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

17

你可以閱讀文檔的命名空間,並且在這樣的查詢使用它:

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