【问题标题】:How to add XML attribute in XML file in C#如何在 C# 中的 XML 文件中添加 XML 属性
【发布时间】:2013-07-01 10:19:17
【问题描述】:

我正在从 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”。 请帮我解决这个问题,我哪里出错了。

【问题讨论】:

标签: c# xml


【解决方案1】:

您需要先将架构添加到 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);

【讨论】:

  • 这没有给出结果:我的预期结果是 ::: w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema">
  • @user2493287 请查看更新的答案,我忘了包含添加 xmlns 属性的行。我也在拍你想要的 xsd 命名空间
  • @user2493287 我的回答不包括它,但您的评论表明您需要在添加eConnectProcessInfo 之前创建SOPTransactionType&gt; 元素
【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多