如何从字符串更新/替换XElement的元素? [英] How can I update/replace an element of an XElement from a string?
问题描述
所以这里是我的情况。
我有一个XElement,我们称它为root,它有后代,它有后代等。我使用LINQ XML,使用 .ToString()
将其加载到备忘录编辑器中,并进行编辑。现在我想用已编辑的版本更新/替换原始的后代元素。
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 a memo editor using .ToString()
and edit it. Now I want to update/replace the original descendent element with the edited version.
让我提到这是一个简单的XML文件,没有模式,不使用DOM,我只需要能够编辑和更新/替换一个元素。
Let me mention that this is a simple XML file, with no schema, not using DOM, etc. I only need to be able to edit and update/replace an element.
这里是我的XML模型:
Here's a mockup 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>
现在我想编辑Pink Floyd元素来纠正Roger Waters的姓氏。我得到那个元素,将其转换为字符串,将其加载到我的编辑器中,进行所需的更改,然后使用 .Parse()
将其转换回XElement。
Now say I want to edit "Pink Floyd" element to correct Roger Waters' last name. I get that element, convert it to a string, load it into my editor, make the changes that I want, and convert it back to an XElement using .Parse()
.
现在,如何更新/替换原始XML中的Pink Floyd节点?
Now, how can I update/replace the "Pink Floyd" node in my original XML?
推荐答案
您可以使用 XElement.ReplaceWith
方法:
You could 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);
您应该添加一些错误检查。我使用 Single
,因为我确定节点存在,但如果有机会,不是你应该使用 SingleOrDefault
并在使用结果之前检查 null
。
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.
此外,如果输入无效,将上述代码包装在try / catch中并处理可能抛出的任何 XmlException
。
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.
这篇关于如何从字符串更新/替换XElement的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!