如何在C#中给XML文件添加XML属性

5

我正在使用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>

期望结果:

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

XML属性在xml文件中没有添加"xsi:nil"。请帮我看看,我做错了什么。


你看过这个吗:https://dev59.com/cHE95IYBdhLWcg3wkeuq - Satpal
2
只是一个提示:使用XLinq(XElement)会更容易。 - H H
2个回答

8

首先,您需要将xsi模式添加到您的文档中。

更新:您还需要将命名空间作为属性添加到根对象中。

//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);

这不会给出结果:我的预期结果是:::<eConnect xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOPTransactionType> <eConnectProcessInfo xsi:nil="true" /> <taRequesterTrxDisabler_Items xsi:nil="true" /> <taUpdateCreateItemRcd xsi:nil="true" /> </SOPTransactionType> </eConnect> - user2493287
@user2493287 请查看更新的答案,我忘记包含添加 xmlns 属性的行。我还将加入您想要的 xsd 命名空间。 - Bob Vale
@user2493287 我的答案不包括它,但是你的评论提示你需要在添加eConnectProcessInfo之前创建 SOPTransactionType> 元素。 - Bob Vale

2
以下是最简单的追加xsi:nil="true"元素的方法:
XmlNode element = null;
XmlAttribute xsinil = doc.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
xsinil.Value = "true";
element.Attributes.Append(xsinil);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接