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

So, here is my case.

I have an XElement, let it root, which has descendants, which have descendants, etc. I pull the descendant using LINQ to XML, load it into the note editor using .ToString() and editing it. Now I want to update / replace the original child element with the edited version.

Let me mention that this is a simple XML file, without a schema, not using the DOM, etc. I only need to edit and update / replace the item.

Here is the layout of my XML:

 <Root> <Genre Name="Rock"> <Artist Name="Pink Floyd"> <BandMembers> <Member>Nick Mason</Member> <Member>Syd Barret</Member> <Member>David Gilmour</Member> <Member>Roger Water</Member> <Member>Richard Wright</Member> </BandMembers> <Category>Favorite band of all time</Category> </Artist> <Artist Name="Led Zepelin"> <Category>Love the band</Category> </Artist> </Genre> <Genre Name="Blues"> <Artist Name="Muddy Waters"> <Instrument>Harmonica</Instrument> </Artist> <Artist Name="Howling Wolf"> <Instrument>Guitar</Instrument> </Artist> </Genre> </Root> 

Now say that I want to edit the Pink Floyd element to fix the name of Roger Waters. I get this element, convert it to a string, load it into my editor, make the necessary changes and convert it back to XElement using .Parse() .

Now, how can I update / replace the "Pink Floyd" node in my source XML?

+6
source share
1 answer

You can use the XElement.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); 

However, you should add some error checking. I used Single , since I am sure that node exists, but if there is a chance that you should not use SingleOrDefault and check for null before using the result.

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

+11
source

Source: https://habr.com/ru/post/886883/


All Articles