C# 向元素添加 XML 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14045967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding XML attribute to an element
提问by Jt2ouan
Looking to add an attribute to an existing xml element <D_COMMS>, not replace the existing attribute just add it to the beginning.
希望向现有 xml 元素添加属性<D_COMMS>,而不是替换现有属性,只需将其添加到开头即可。
This is the XML
这是 XML
<OUTPUT version="2.0">
<RESPONSE>
<DATA id="17fb13cca6c5463597fdf340c044069f">
<![CDATA[<ID> jdfkldklfjdkl</ID><D_COMMS>ON this date...</D_COMMS>]]>
</DATA>
</RESPONSE>
This XML is the result of a HTTPWebResponse so this is what the XMl looks like when it comes back to me and I need to add a value to the D_COMMS element and send it back.Tried something like this to look for the descendant DATA and add it that way.
这个 XML 是 HTTPWebResponse 的结果,所以这就是 XMl 返回给我时的样子,我需要向 D_COMMS 元素添加一个值并将其发送回来。尝试过这样的事情来查找后代 DATA 并添加就这样。
var addelement = doc.Descendants("DATA").First();
addelement.Add(XElement("D_COMMS","On this date we said"));
采纳答案by jam40jeff
You can find the DATA node and add an attribute as follows:
可以找到DATA节点,添加一个属性如下:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList dataNodes = doc.GetElementsByTagName("DATA");
if (dataNodes != null && dataNodes.Count > 1)
{
dataNodes[0].Attributes.Append(doc.CreateAttribute("D_COMMS", "On this date we said"));
}
回答by FJ Chen
A better one to set attribute is in here Adding attributes to an XML node
设置属性的更好方法是在此处将属性添加到 XML 节点
XmlElement id = doc.CreateElement("id");
id.SetAttribute("userName", "Tushar");

