[英]How to update XmlNode attribute values in C#
我有一个像这样的XML文件:
<caseData>
<entity type="case" name="1">
<attribute name="CASE_OPEN" value="false"/>
<attribute name="CASE_NUMBER" value=""/>
<attribute name="CASE_TYPE" value=""/>
</entity>
<caseData>
我需要更新CASE_NUMBER和CASE_TYPE的值。 我只能做的方法是:
_xd = new XmlDocument();
_xd.LoadXml(xmlTemplate);
var caseitem = _xd.GetElementsByTagName("entity")[0];
var childnodes = caseitem.ChildNodes;
foreach (XmlNode node in childnodes)
{
if (node.Attributes["name"].Value == "CASE_NUMBER")
{
node.Attributes["value"].Value = "11222";
}
if (node.Attributes["name"].Value == "CASE_TYPE")
{
node.Attributes["value"].Value = "NEW";
}
}
我想知道是否有更好的方法可以做到这一点。 谢谢!
另一个选择是使用LINQ to XML。 通常,它是一个更好的API,可用于:
var doc = XDocument.Parse(xmlTemplate);
var caseNumber = doc
.Descendants("attribute")
.Single(e => (string)e.Attribute("name") == "CASE_NUMBER");
caseNumber.SetAttributeValue("value", "11222");
如果这确实是模板,而您只是填补空白,则可以很容易地从头开始创建它:
var attributes = new Dictionary<string, string>
{
{"CASE_OPEN", "false"},
{"CASE_NUMBER", "11122"},
{"CASE_TYPE", "NEW"}
};
var caseData = new XElement("caseData",
new XElement("entity",
new XAttribute("type", "case"),
new XAttribute("name", "1"),
AttributeElements(attributes)
)
);
其中AttributeElements
类似于:
private static IEnumerable<XElement> AttributeElements(
IReadOnlyDictionary<string, string> attributes)
{
return attributes.Select(x => new XElement("attribute",
new XAttribute("name", x.Key),
new XAttribute("value", x.Value)
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.