如何在使用XPathNodeIterator进行迭代时修改节点值?

时间:2010-09-09 16:53:44

标签: c# xml xpath xpathdocument xpathnodeiterator

我正在使用XPathNodeIterator导航XML文档,我想更改一些节点的值。 我无法弄清楚如何:(

这是我正在使用的代码:

XPathDocument docNav = new XPathDocument(path);

XPathNavigator nav = docNav.CreateNavigator();
nav.MoveToRoot();

XPathNodeIterator itemsIterator = nav.Select("/foo/bar/item");
while (mediumsIterator.MoveNext())
{
    XPathNodeIterator subitemsIterator = itemsIterator.Current.Select("SubitemsList/name");
    while (subitemsIterator.MoveNext())
    {
        XPathNodeIterator nodesIterator = itemsIterator.Current.Select("Param");
        nodesIterator.MoveNext();
        String the_params = nodesIterator.Current.Value;

        // check if I need to modify nodesIterator.Current.Value
        // ...
        // ok I do - how?
    }
}

XML文件示例:

<?xml version="1.0" encoding="utf-8"?>
<foo>
  <bar>
    <item>
      <Param />
      <SubitemsList>
        <name>name one</name>
        <name>name two</name>
        ...
      </SubitemsList>
    </item>
    ...
  </bar>
</foo>

或许有更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

我找到了一种方法:

  1. XPathDocument替换为XmlDocument
  2. 当我到达所需节点时
  3. ...

    XmlNode node = ((IHasXmlNode)nodesIterator.Current).GetNode();
    node.InnerText = "new text";