How can I update/replace an element of an XElement from a string?

前端 未结 1 1871
悲&欢浪女
悲&欢浪女 2020-12-20 15:59

So here\'s my case.

I have an XElement, let\'s call it root, which has descendents, which have descendents, etc. I pull a descendent using LINQ to XML, load it into

相关标签:
1条回答
  • 2020-12-20 16:29

    You could use the XNode.ReplaceWith method:

    // input would be your edited XML, this is just sample data to illustrate
    string input = @"<Artist Name=""Pink Floyd"">
      <BandMembers>
        <Member>Nick Mason</Member>
        <Member>Syd Barret</Member>
        <Member>David Gilmour</Member>
        <Member>Roger Waters</Member>
        <Member>Richard Wright</Member>
      </BandMembers>
      <Category>Favorite band of all time</Category>
    </Artist>";
    
    var replacement = XElement.Parse(input);
    var pinkFloyd = xml.Elements("Genre")
                       .Where(e => e.Attribute("Name").Value == "Rock")
                       .Elements("Artist")
                       .Single(e => e.Attribute("Name").Value == "Pink Floyd");
    
    pinkFloyd.ReplaceWith(replacement);
    Console.WriteLine(xml);
    

    You should add some error checking though. I used Single since I'm sure the node exists, but if there's a chance it isn't you should use SingleOrDefault and check for null before using the result.

    Also, if the input is invalid you'll need to wrap the above code in a try/catch and handle any XmlException that might be thrown.

    0 讨论(0)
提交回复
热议问题