2017-08-10 103 views
0

創建沒有前綴的根節點的正確方法是什麼,但是讓它顯示xmlns:xsi="blah"?基本上,我想是這樣的:如何用xmlns:xsi創建根節點,但沒有前綴?

<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" version="0.95"> 
    <Whatever> 
    </Whatever> 
</EDSCrate> 

不過,我嘗試過很多辦法,它只是不會給我一個簡單的節點沒有命名空間,即使是這樣,它不會給我屬性中正確的xmlns:xsi

我想避免任何黑客重寫ToString並替換我自己在XmlWriter中的文本。

string uri = "http://www.w3.org/2001/XMLSchema-instance"; 

XmlDocument doc = new XmlDocument(); 
doc.PreserveWhitespace = true; 
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null)); 

nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("xsi", uri); 

XmlElement root = doc.CreateElement("EDSCrate", uri); 
// at this point, it already added xmlns="http://www.w3.org/2001/XMLSchema-instance" without me doing anything 
root.RemoveAllAttributes(); 
// but i want xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"!! 
root.SetAttribute("xmlns:xsi", uri); 
root.SetAttribute("xsi:noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd"); 

回答

1
string uri = "http://www.w3.org/2001/XMLSchema-instance"; 

var doc = new XmlDocument(); 
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null)); 

var root = doc.CreateElement("EDSCrate"); 
doc.AppendChild(root); 
root.AppendChild(doc.CreateElement("Whatever")); 

var attr = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation", uri); 
attr.InnerText = "EDS_Crate_2010-02-10.xsd"; 
root.SetAttributeNode(attr); 

root.SetAttribute("version", "0.95"); 
+0

這是什麼,所以如果我通過CreateElement作爲參數傳遞uri,它只會放'xmlns:'但如果我沒有通過uri,那麼它會從命名空間管理器中抓取它並將'xmlns:xsi'? !?! – codenamezero

1

我發現使用Linq2Xml更容易。

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 

var xdoc = new XDocument(
       new XElement(
        "EDSCrate", 
        new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
        new XAttribute(xsi + "noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd"), 
        new XAttribute("version", "0.95"), 
        new XElement("Whatever","") 
       ) 
      ); 
var xml = xdoc.ToString(); 

OUTPUT:

<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" 
      version="0.95"> 
    <Whatever></Whatever> 
</EDSCrate> 
+0

我沒有嘗試使用LINQ,但我敢肯定,你的解決方案的工作呢! – codenamezero