What's the most efficient way to locate and set element values in an XDocument?

前端 未结 1 1169
孤街浪徒
孤街浪徒 2021-01-24 17:21

Given the following XML \'template\':


  
     

        
相关标签:
1条回答
  • 2021-01-24 17:52

    Does this do it for you? Good old Descendants property.

    string xmlInput = ...;
    XDocument myDoc = XDocument.Parse(xmlInput);
    //
    List<XElement> someElements = myDoc.Descendants("a").ToList();
    someElements.ForEach(x => x.Value = "Foo");
    //
    Console.WriteLine(myDoc);
    

    Hmm, I see you have an attribute in there. Can do that too:

    string xmlInput = //...
    XDocument myDoc = XDocument.Parse(xmlInput);
    //
    List<XText> someText =
      myDoc.Descendants()
      .Nodes()
      .OfType<XText>()
      .Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
      .ToList();
    //
    List<XAttribute> someAttributes =
      myDoc.Descendants()
      .Attributes()
      .Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
      .ToList();
    //
    someText.ForEach(x => x.Value = "Foo");
    someAttributes.ForEach(x => x.Value = "Bar");
    //
    Console.WriteLine(myDoc);
    

    Ah, now with what you're expecting, I will make it work:

    List<XElement> e = myDoc.Descendants("a").ToList();
    e.Where(x => x.Attribute("name").Value == "username").Single().Value = "abc";
    e.Where(x => x.Attribute("name").Value == "password").Single().Value = "abc";
    
    0 讨论(0)
提交回复
热议问题