2011-06-01 143 views
3

考慮以下XMLXPath:根據另一個節點選擇一個節點?

<Items> 
    <Item> 
     <Code>Test</Code> 
     <Value>Test</Value> 
    </Item> 
    <Item> 
     <Code>MyCode</Code> 
     <Value>MyValue</Value> 
    </Item> 
    <Item> 
     <Code>AnotherItem</Code> 
     <Value>Another value</Value> 
    </Item> 
</Items> 

我想選擇具有Code節點與價值MyCodeItemValue節點。我將如何去使用XPath

我試過使用Items/Item[Code=MyCode]/Value,但它似乎並沒有工作。

+1

嘗試在astring中設置MyCode,就像這個「MyCode」一樣,如果有可能,我會推薦使用[Linq-to-XML](http://msdn.microsoft.com/zh-cn/library/bb387098。 ASPX)。 – 2011-06-01 15:29:02

+0

這個「XML」是一團糟 - 現在已經形成了! – alexbrn 2011-06-01 15:33:03

+0

@alexbrn:壞XML很可能是問題的一部分,所以應該在答案中(在這種情況下)。例如,我在回答中已經解決了這個問題。我建議留下這個問題是如何被問到的。 – 2011-06-01 15:36:53

回答

7

您的XML數據有誤。 Value標籤沒有正確匹配的結束標籤,而您的Item標籤沒有匹配的結束標籤(</Item>)。

至於你的XPath,儘量封閉要匹配引號中的數據:

const string xmlString = 
@"<Items> 
    <Item> 
     <Code>Test</Code> 
     <Value>Test</Value> 
    </Item> 
    <Item> 
     <Code>MyCode</Code> 
     <Value>MyValue</Value> 
    </Item> 
    <Item> 
     <Code>AnotherItem</Code> 
     <Value>Another value</Value> 
    </Item> 
</Items>"; 

var doc = new XmlDocument(); 
doc.LoadXml(xmlString); 
XmlElement element = (XmlElement)doc.SelectSingleNode("Items/Item[Code='MyCode']/Value"); 
Console.WriteLine(element.InnerText); 
+0

似乎引號是問題。 – 2011-06-01 15:38:10

+1

是的,沒有引號會試圖比較節點代碼的值和節點MyCode的值。正如所料,它沒有找到一個名爲MyCode的節點。 – 2011-06-03 09:52:12

1

您需要:

/Items/Item[Code="MyCode"]/Value

假設你解決,你的XML:

<?xml version="1.0"?> 
<Items> 
    <Item> 
    <Code>Test</Code> 
    <Value>Test</Value> 
    </Item> 
    <Item> 
    <Code>MyCode</Code> 
    <Value>MyValue</Value> 
    </Item> 
    <Item> 
    <Code>AnotherItem</Code> 
    <Value>Another value</Value> 
    </Item> 
</Items>
相關問題