2013-07-01 65 views
4

我從C#代碼生成XML文件,但是當我將屬性添加到XML節點時出現問題。以下是代碼。如何在C#中的XML文件中添加XML屬性

XmlDocument doc = new XmlDocument(); 
XmlNode docRoot = doc.CreateElement("eConnect"); 
doc.AppendChild(docRoot); 
XmlNode eConnectProcessInfo = doc.CreateElement("eConnectProcessInfo"); 
XmlAttribute xsiNil = doc.CreateAttribute("xsi:nil"); 
xsiNil.Value = "true"; 
eConnectProcessInfo.Attributes.Append(xsiNil); 
docRoot.AppendChild(eConnectProcessInfo); 

結果:

<eConnect> 
    <eConnectProcessInfo nil="true"/> 
</eConnect> 

預期的結果:XML文件: 「無XSI」

<eConnect> 
    <eConnectProcessInfo xsi:nil="true"/> 
</eConnect> 

XML屬性不加入。 請幫我解決這個問題,我錯了。

+0

你有沒有看到:HTTP:/ /stackoverflow.com/questions/2255311/how-to-create-xmlelement-attributes-with-prefix – Satpal

+2

只是一個提示:使用XLinq('XElement')更簡單 –

回答

5

您需要的模式添加到您的文檔XSI第一

UPDATE,你還需要將命名空間的屬性添加到根對象

//Store the namespaces to save retyping it. 
string xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
string xsd = "http://www.w3.org/2001/XMLSchema"; 
XmlDocument doc = new XmlDocument(); 
XmlSchema schema = new XmlSchema(); 
schema.Namespaces.Add("xsi", xsi); 
schema.Namespaces.Add("xsd", xsd); 
doc.Schemas.Add(schema); 
XmlElement docRoot = doc.CreateElement("eConnect"); 
docRoot.SetAttribute("xmlns:xsi",xsi); 
docRoot.SetAttribute("xmlns:xsd",xsd); 
doc.AppendChild(docRoot); 
XmlNode eConnectProcessInfo = doc.CreateElement("eConnectProcessInfo"); 
XmlAttribute xsiNil = doc.CreateAttribute("nil",xsi); 
xsiNil.Value = "true"; 
eConnectProcessInfo.Attributes.Append(xsiNil); 
docRoot.AppendChild(eConnectProcessInfo); 
+0

這不是結果:我的預期結果是::: user2493287

+0

@ user2493287請參閱更新後的答案,我忘記添加添加xmlns屬性的行。我也在拍你想要的xsd命名空間 –

+0

@ user2493287我的回答並不包括它,但是你的評論表明你需要在添加'eConnectProcessInfo'之前創建'SOPTransactionType>'元素。 –

相關問題