关于C#中XPathNodeIterator问题的问题

时间:2010-12-23 09:03:51

标签: c# c#-2.0 xpathnodeiterator

我正在解析一个Xml文件。我在如何在C#2.0中更合理地使用XPathNodeIterator MoveNext()时遇到了麻烦。

我的代码就是这样,

while (it.MoveNext())
{


string str = it.Current.GetAttribute("id", it.Current.NamespaceURI);

it.Current.MoveToChild("item", "");

// do someting....
// My XMl file is a complex Xml file. I must Move to multi layer Child with *MoveToChild()*.
// After that, I must add several *MoveToParent()* in different Layers to make sure the *it* still meet for the use of while loop.
// I think it doesn't make sense like this.
// Some time. the *it* can't still direct to my original layer. While-Loop doesn't work well.

}

我试图声明一个新的XPathNodeIterator对象 tempIt

while (it.MoveNext())
{

    XPathNodeIterator tempIt;
    tempIt= it;

    string str = tempIt.Current.GetAttribute("id", tempIt.Current.NamespaceURI);

    tempIt.Current.MoveToChild("item", "");

    // Now I chech *it* on here, I found the *it* also changed it's *current* and "position". and it's count also changed. 
    // I don't know why.

}

如何解决此问题?

感谢您的意见和建议。

1 个答案:

答案 0 :(得分:2)

也许这可以帮助

while (nodeIterator.MoveNext())
{
    XPathNavigator n = nodeIterator.Current;
    Console.WriteLine(n.LocalName);
}


XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator nodes = navigator.Select("/bookstore/book");
nodes.MoveNext();
XPathNavigator nodesNavigator = nodes.Current;

XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);

while (nodesText.MoveNext())
    Console.WriteLine(nodesText.Current.Value);

和books.xml

<?xml version="1.0" encoding="utf-8" ?> 
<bookstore>
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>