2013-07-01 60 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>'元素。 –

相关问题