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

前端 未结 1 1168
孤街浪徒
孤街浪徒 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 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 someText =
      myDoc.Descendants()
      .Nodes()
      .OfType()
      .Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
      .ToList();
    //
    List 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 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)
提交回复
热议问题