2011-12-09 70 views
2

我正在將XmlElement添加到現有文檔,但正在添加一個額外的屬性。下面是代碼:爲什麼.NET XML將xlmns屬性附加到我添加到文檔中的XmlElements?我可以阻止它嗎?

XmlNode manifest = this.getManifestNode(); 
XmlElement manifestEntry = _content.CreateElement ("item", _contentPath); 
XmlAttribute id = _content.CreateAttribute ("id"); 
id.Value = "content" + getManifestNodes().Count; 
XmlAttribute href = _content.CreateAttribute ("href"); 
href.Value = splitPath [splitPath.Length - 1]; 
XmlAttribute mediaType = _content.CreateAttribute ("media-type"); 
mediaType.Value = "application/xhtml+xml"; 
manifestEntry.Attributes.Append (id); 
manifestEntry.Attributes.Append (href); 
manifestEntry.Attributes.Append (mediaType); 
manifest.AppendChild (manifestEntry); 

和生成的XML:

<item id="content3" href="test1.html" media-type="application/xhtml+xml" xmlns="/home/jdphenix/epubtest/test/OEBPS/content.opf" /> 

哪裏

xmlns="/home/jdphenix/epubtest/test/OEBPS/content.opf" 

來自哪裏?它添加的路徑是文件在磁盤上的位置,但我沒有將它添加到我的代碼中(至少,我知道)。讓我知道你是否需要了解更多細節。

編輯:我修改了代碼,每Filburt的建議,改變了

XmlElement manifestEntry = _content.CreateElement ("item", _contentPath); 

XmlElement manifestEntry = _content.CreateElement ("item"); 

這是朝着正確方向邁出的一步,但產生以下XML:

<item id="content3" href="test1.html" media-type="application/xhtml+xml" xmlns="" /> 
+0

我的空白xmlns屬性的問題可能是http://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument的重複,看現在進入它 – jdphenix

+0

發生這種情況是因爲.NET的Xml類正確對待xmlns。這個「問題」是由於我對XML命名空間缺乏瞭解而造成的。 輸出產生一個空白xmlns屬性條目,因爲通過調用 來通知它這樣做。XmlElement manifestEntry = _content.CreateElement(「item」); 而不是 XmlElement manifestEntry = _content.CreateElement(「item」,「http://www.idpf.org/2007/opf」); 我沒有提供我原始問題中的詳細信息以正確回答。請參閱http://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument。 – jdphenix

回答

2

你自己添加這個命名空間(第2行):

XmlElement manifestEntry = _content.CreateElement ("item", _contentPath); 

XmlDocument.CreateElement Method (String, String) - 第一個字符串參數是要添加的元素和第二串的限定名稱的命名空間。

嘗試

XmlElement manifestEntry = _content.CreateElement ("item"); 

,一切都應該罰款。

+0

指出我在正確的方向,謝謝 – jdphenix

相關問題