2016-08-02 9 views
0

の属性値。私ができる方法は:は、私はこのようなXMLファイルを持っているのC#

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

      } 

もっと良い方法があるのでしょうか。 ありがとう!

答えて

1

もう1つのオプションは、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) 
    )); 
} 
+0

ありがとう! – user1015413

関連する問題