2016-08-02 15 views
0

Ich habe eine XML-Datei wie folgt:Wie XmlNode aktualisieren Attributwerte in C#

<caseData> 
    <entity type="case" name="1"> 
    <attribute name="CASE_OPEN" value="false"/> 
    <attribute name="CASE_NUMBER" value=""/> 
    <attribute name="CASE_TYPE" value=""/> 
    </entity> 
<caseData> 

Ich brauche den Wert für die CASE_NUMBER und CASE_TYPE zu aktualisieren. Die Art, wie ich nur tun kann, ist:

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

      } 

Ich frage mich, ob es einen besseren Weg gibt, es zu tun. Danke!

Antwort

1

Eine andere Option ist die Verwendung von LINQ to XML. Es ist generell eine schönere API für die Arbeit mit:

var doc = XDocument.Parse(xmlTemplate); 

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

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

Wenn dies wirklich eine Schablone und Sie sind nur in den Lücken ausfüllen, können Sie ziemlich leicht erstellen, es von Grund auf neu:

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

Wo AttributeElements ist etwas wie:

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) 
    )); 
} 
+0

Es funktioniert! Vielen Dank! – user1015413

Verwandte Themen