简体   繁体   English

如何在C#中更新XmlNode属性值

[英]How to update XmlNode attribute values in C#

I have an XML file like this: 我有一个像这样的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>

I need to update the value for the CASE_NUMBER and CASE_TYPE. 我需要更新CASE_NUMBER和CASE_TYPE的值。 The way I only can do is: 我只能做的方法是:

    _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";
                }

            }

I am wondering if there is a better way to do it. 我想知道是否有更好的方法可以做到这一点。 Thanks! 谢谢!

Another option is using LINQ to XML. 另一个选择是使用LINQ to XML。 It's generally a nicer API to work with: 通常,它是一个更好的API,可用于:

var doc = XDocument.Parse(xmlTemplate);

var caseNumber = doc
    .Descendants("attribute")
    .Single(e => (string)e.Attribute("name") == "CASE_NUMBER");

caseNumber.SetAttributeValue("value", "11222");

If this really is a template and you're just filling in the blanks, you can pretty easily just create it from scratch: 如果这确实是模板,而您只是填补空白,则可以很容易地从头开始创建它:

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

Where AttributeElements is something like: 其中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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM