2013-09-25 39 views
0

您好我正在使用XPathNodeIterator在XML文檔下的XML節點列表中進行迭代。當條件匹配時迭代,我需要在當前節點下的特定值。取而代之的,是的SelectSingleNode返回從其它父節點節點...讓我舉一個例子:當我在XPathNodeIterator.Current.SelectSingleNode下搜索時,它只是在整個XML文檔中搜索

XPathNavigator SourceReqNav = // Load this using an xml; 
XmlNamespaceManager manager = new XmlNamespaceManager(SourceReqNav.NameTable); 
SourceReqNav.MoveToRoot(); 
XPathNodeIterator nodeIterator = SourceReqNav.Select(parentPath, manager); 

while (nodeIterator.MoveNext()) 
{ 
//If condition matches at nodeIterator.Current node, Executing a partial xpath related to 
//only that current node 

XPathNavigator singleNode = nodeIterator.Current.SelectSingleNode(xpath, namespaceManager); 

// Here at above line, It should return null as Child node doesn't exist but It 
// searches in whole xml and finding the matching one..even though the XPATH is kind of 
// partial and applicable to only that node structure. 
} 

示例XML:

<RootNode> 
<Element id=1> 
    <Address> 
    <Name>  </Name> 
    <ZipCode>456</ZipCode> 
    <Street> </Street> 
    </Address> 
</Element> 
<Element id=2> 
</Element> 
<Element id=3> </Element> 
</RootNode> 

比方說,我遍歷所有的「元素」,並試圖找到元素id = 2的「地址」。 現在,迭代時讓我們說我在「元素id = 2」。當我找到節點時,我會從當前節點(nodeIterator.Current)中選擇一個名爲「Zip」的節點。爲此,我使用xpath作爲「/ Address/ZipCode」(格式可能是錯誤的,因爲這只是例子)。在這種情況下,它應該返回我空,而是從「元素ID = 1」返回郵編

任何幫助將是可觀的..

+1

我希望更多的人瞭解'XElement'如何使用LINQ。 – gunr2171

+0

那麼,我確實使用LINQ to XML。但是這是更加可定製的框架努力的一部分,用戶可以簡單地使用XPATH(擴展)通過配置文件更改映射。無論如何,這不是我要找的。我很欣賞你花時間去看看。 – Reg

回答

0

由於時間的限制(用於修復),我帶着小更長的路線。 而不是直接在當​​前節點搜索,我從當前節點獲得SubTree(類型:XmlReader)並使用它加載XPathDocument。從它創建一個XPathNavigator。比它應用相同的部分XPath。

nodeIterator.Current.SelectSingleNode(xpath, namespaceManager); 

這已修改爲:

XmlReader sourceReader = nodeIterator.Current.ReadSubtree(); 
XPathDocument doc = new XPathDocument(sourceReader); 
XPathNavigator sourceNavigator = doc.CreateNavigator(); 
sourceNavigator.SelectSingleNode(xpath, namespaceManager); 

我還是想避開它,如果有人有更好的答案。希望這會幫助某人。