在 C# 中替换 xml 元素值

Raj*_*Raj 2 c# xml linq-to-entities xmldocument xml-parsing

这是我的 xml 文件数据

<Persons>
    <Person>
        <Name>john</Name>
    </Person>
    <Employee>
        <Detail>
            <Firstname>john</FirstName>
        </Detail>
    </Employee>
    <Student>
        <FullName>john</FullName>
    </Student>
</Persons>
Run Code Online (Sandbox Code Playgroud)

我想在所有地方将“john”替换为“danny”。

我怎样才能在 c# 中做到这一点?

har*_*r07 8

一种可能的方式使用XDocument

var doc = XDocument.Load("path_to_xml_file.xml");

//select all leaf elements having value equals "john"
var elementsToUpdate = doc.Descendants()
                          .Where(o => o.Value == "john" && !o.HasElements);

//update elements value
foreach(XElement element in elementsToUpdate)
{
    element.Value = "danny";
}

//save the XML back as file
doc.Save("path_to_xml_file.xml");
Run Code Online (Sandbox Code Playgroud)

请注意,它XElement.Value包含元素内的所有文本节点,并连接

其意义在于,例如,考虑您的 XML 作为输入,不仅<Name>具有“john”值,而且还具有<Person>. 但我们只想更新叶子元素而不是祖先。

*)我假设您并不是真的打算通过来标记问题,因此这个答案使用较新的 XML API XDocument,尽管使用 XmlDocument 也是可能的。