

新闻资讯
技术学院应使用XDocument或XmlDocument解析XML后安全替换,而非字符串替换;支持替换元素值、属性值及纯文本节点,需注意命名空间、混合内容处理和大文件流式处理。
在C#中对XML文件进行查找并替换文本内容,关键在于区分“替换元素/属性的值”和“替换XML中的纯文本节点”。直接用字符串替换(如File.ReadAllText().Replace())容易破坏XML结构,不推荐。应使用XML解析器(如XDocument或XmlDocument)安全遍历并修改节点。
适用于已知元素路径(如、),需精准定位并更新其内部文本值。
XDocument.Load()加载XML文件Descendants("ElementName")查找所有匹配元素node.Nodes().OfType() 或直接用node.Value获取/设置文本Save()写回文件示例:将所有元素的文本从"OldName"改为"NewName"
XDocument doc = XDocument.Load("data.xml");
foreach (var nameNode in doc.Descendants("Name"))
{
if (nameNode.Value == "OldName")
nameNode.Value = "NewName";
}
doc.Save("data.xml");
当目标是修改属性(如id="123"、status="pending")时,需定位到XAttribute对象。
Elements().Attributes("AttributeName")或Descendants().Attributes()筛选attribute.Value读取和赋值示例:把所有type="legacy"改为type="modern"
foreach (var attr in doc.Descendants().Attributes("type"))
{
if (attr.Value == "legacy")
attr.Value = "modern";
}
当XML存在混合内容(如 Hello world!),文本分散在多个XText节点中,需遍历所有文本节点。
doc.DescendantNodes().OfType() 获取全部文本节点XText调用Replace(),但注意:不能直接改node.Value(只读),需用node.ReplaceWith()
示例:仅在元素内替换"error"为"warning"
foreach (var content in doc.Descendants("Content"))
{
var textNodes = content.Nodes().OfType().ToList();
foreach (var textNode in textNodes)
{
string updated = textNode.Value.Replace("error", "warning");
textNode.ReplaceWith(new XText(updated));
}
}
XML不是普通文本,操作不当会导致格式错误或数据丢失。
string.Replace()直接处理整个XML字符串——会误改标签名、属性名或CDATA内容ToString()预览变更XNamespace,否则Descendants("Item")可能找不到节点XDocument(内存加载),可考虑XmlReader/XmlWriter流式处理