找到xml节点的更好方法?

时间:2022-06-06 12:37:20

Can anyone tell me if there is a better way to search an XML file and replace a value? The node could exist anywhere, so can't use xpath.

谁能告诉我是否有更好的方法来搜索XML文件并替换值?节点可以存在于任何地方,因此不能使用xpath。

I can achieve what I want with the following, but just wondering if there is an easier way.

我可以通过以下方式实现我想要的,但只是想知道是否有更简单的方法。

 XmlDocument doc = new XmlDocument();
 doc.Load("c:\\test.xml");

 XmlNodeList elemList = doc.GetElementsByTagName("NameToChange");

 for (int i=0; i < elemList.Count; i++)
 {   
     elemList[i].InnerText = "replacedText";
 }  

TIA

TIA

Dave

戴夫

2 个解决方案

#1


0  

Actually, I think there's no problem with unspecified location when it comes to XPath. Just use the descendant direction http://www.tizag.com/xmlTutorial/xpathdescendant.php

实际上,我认为在XPath方面,未指定的位置没有问题。只需使用后代方向http://www.tizag.com/xmlTutorial/xpathdescendant.php

The XPath would be:

XPath将是:

//NameToChange

But your solution seems OK if you ask me. The way you did it seems easy.

但是如果你问我,你的解决方案似乎没问题。你做的方式似乎很容易。

The main difference that could result from using one solution or the other would be in the difficulty of implementing any changes in the way you want to select your nodes. I'm not familiar with C# libraries but XPath lets you do almost anything in a single line, when it comes to selection of elements.

使用一个解决方案或另一个解决方案可能导致的主要区别在于难以实现您想要选择节点的方式的任何更改。我不熟悉C#库,但是在选择元素时,XPath几乎可以让你在一行中做任何事情。

#2


1  

Use LINQ to XML and the XElement etc classes. Personally, I prefer it to XPath because it's integrated directly into the language, instead of relying on strings.

使用LINQ to XML和XElement等类。就个人而言,我更喜欢XPath,因为它直接集成到语言中,而不是依赖于字符串。

#1


0  

Actually, I think there's no problem with unspecified location when it comes to XPath. Just use the descendant direction http://www.tizag.com/xmlTutorial/xpathdescendant.php

实际上,我认为在XPath方面,未指定的位置没有问题。只需使用后代方向http://www.tizag.com/xmlTutorial/xpathdescendant.php

The XPath would be:

XPath将是:

//NameToChange

But your solution seems OK if you ask me. The way you did it seems easy.

但是如果你问我,你的解决方案似乎没问题。你做的方式似乎很容易。

The main difference that could result from using one solution or the other would be in the difficulty of implementing any changes in the way you want to select your nodes. I'm not familiar with C# libraries but XPath lets you do almost anything in a single line, when it comes to selection of elements.

使用一个解决方案或另一个解决方案可能导致的主要区别在于难以实现您想要选择节点的方式的任何更改。我不熟悉C#库,但是在选择元素时,XPath几乎可以让你在一行中做任何事情。

#2


1  

Use LINQ to XML and the XElement etc classes. Personally, I prefer it to XPath because it's integrated directly into the language, instead of relying on strings.

使用LINQ to XML和XElement等类。就个人而言,我更喜欢XPath,因为它直接集成到语言中,而不是依赖于字符串。