如何解决使用C#遍历XML文档,如果满足条件,则替换值或节点
我有一个带有XML XDocument xdoc1 = XDocument.Load(doc1)
的 XDocument
我想遍历XML文档,如果满足条件,请替换值或节点。
我尝试了如下代码:
var list = from item in xdoc1.Root.Element("New").Elements() select item;
foreach (XElement item in list)
{
foreach (var node in item.Nodes())
{
if (node.ToString() == "DIV||<Control>")
{
item.Element("Value").Value = "DIV||TextBox";
}
}
但这对我不起作用。
如果我的XML像这样
<Test>
<New>
<DoSometing>
<Selector>
</Selector>
<Value>DIV||<Control></Value>
</DoSometing>
<DoSometingElse>
<Selector>
</Selector>
<Value>DIV||<Control></Value>
</DoSometingElse>
</New>
</Test>
所以我的想法是循环遍历所有xml,如果条件==
<Control>
然后将其替换。
我也尝试过像IEnumerable<XElement> list = from item in xdoc1.Root.Element("New").Elements() where (item.Name == "Value") select item;
解决方法
您可能考虑过滤查询块中的元素,并且仅将更新应用于必要的元素。请注意,此处使用XElement.Value
,因此必须使用解码后的元素值。
var list = from item in xdoc1.Root.Element("New").Elements().Elements("Value")
where item.Value == "DIV||<Control>"
select item;
foreach (XElement item in list)
{
item.Value = "DIV||TextBox";
}
,
更简单的版本。
c#
void Main()
{
const string fileName = @"e:\temp\hala.xml";
const string searchFor = "DIV||<Control>";
const string replaceWith = "789";
//XDocument xdoc = XDocument.Load(fileName);
XDocument xdoc = XDocument.Parse(@" < Test >
<New>
<DoSometing>
<Selector>
</Selector>
<Value>DIV||<Control></Value>
</DoSometing>
<DoSometingElse>
<Selector>
</Selector>
<Value>DIV||<Control></Value>
</DoSometingElse>
</New>
</Test>");
// step #1: find element(s) based on the search value
var xmlFragment = xdoc.Descendants("Value")
.Where(d => d.Value.Equals(searchFor));
// step #2: if found,set its value
foreach (XElement element in xmlFragment)
{
element.SetValue(replaceWith);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。