使用XmlDocument在C#中生成带属性XML节点的正确代码
解决C# XmlDocument生成带属性的XML元素问题
你现在遇到的问题很明确:想要生成带value属性的XML元素(比如<system value="https://somethingichanged" />),但当前代码把值当成了元素的文本内容,生成了<system>https://somethingichanged</system>这种结构。核心原因是你用InnerText把值放到了元素内部,而不是给元素添加属性节点。
要修正这个问题,我们需要创建XmlAttribute节点,把值绑定到属性上,再将属性附加到对应的元素中。下面是修改后的完整代码:
string[] tag = new string[] { "service", "coding", "system", "code", "http://URI"}; XmlElement Service = m_XMLDoc.CreateElement(tag[0], tag[4]); XmlElement Coding = m_XMLDoc.CreateElement(tag[1], tag[4]); Service.AppendChild(Coding); // 创建system元素并添加value属性 XmlElement systemElement = m_XMLDoc.CreateElement(tag[2], tag[4]); XmlAttribute systemValueAttr = m_XMLDoc.CreateAttribute("value"); systemValueAttr.Value = "https://somethingichanged"; systemElement.Attributes.Append(systemValueAttr); Coding.AppendChild(systemElement); // 创建code元素并添加value属性 XmlElement codeElement = m_XMLDoc.CreateElement(tag[3], tag[4]); XmlAttribute codeValueAttr = m_XMLDoc.CreateAttribute("value"); codeValueAttr.Value = myTSS[i].ToString(); codeElement.Attributes.Append(codeValueAttr); Coding.AppendChild(codeElement);
关键修改说明:
- 替换了原来的
XmlNode为XmlElement,操作元素属性时更直观(当然用XmlNode也能实现,只是XmlElement更贴合元素操作场景) - 为每个目标元素单独创建
value属性节点,通过Value属性赋值 - 调用
Attributes.Append()将属性绑定到对应的元素上
这样生成的XML就会完全符合你的预期:
内容的提问来源于stack exchange,提问作者V.Kirsch
相关产品推荐
相关产品推荐

