2011-11-07 23 views
0

我有一个XML文件是这样的:如何将XML节点内部文本与相同的后代进行比较?

<Tests> 
    <Test> 
     <Name>Test1</Name> 
     <Type>A</Type> 
    </Test> 
    <Test> 
     <Name>Test2</Name> 
     <Type>A</Type> 
    </Test> 
    <Test> 
     <Name>Test3</Name> 
     <Type>B</Type> 
    </Test> 
</Tests> 

我怎样才能返回一个字符串数组或列表,它仅包含Test这theire类型为A的名字吗?

我正在尝试使用此代码,但没有成功!

XPathNodeIterator it = nav.Select("/Tests/Test[Type = 'A']/Name) 
+0

您的XPath表达式是正确的。你能否详细说明“不成功”是什么意思? –

+0

目前它返回所有'Name'节点,我会再看一遍并回报。 –

+0

这是因为您的XPath表达式确实匹配'Name'元素。您应该移除'/ Name'来代替'Test'元素。 –

回答

1

在你的问题中的XPath表达式匹配Name元素。如果你想匹配Test元素代替,你必须删除/Name部分:

XPathNodeIterator it = nav.Select("/Tests/Test[Type = 'A']); 

如果你想使用XPathNavigator,从那里,你可以调用MoveToChild()到导航指向Name元素:

foreach (XPathNavigator elemNav in it) { 
    elemNav.MoveToChild("Name", ""); 
    string name = elemNav.Value; 
    // Do something with 'name'... 
} 
2

难道你不想试试linq2xml吗?

using System.Xml.Linq; 
using System.Linq; 

///////////

XElement root = new XElement("Tests", 
    new XElement("Test", 
    new XElement("Name", "Test1"), 
    new XElement("Type", "A")), 
    new XElement("Test", 
    new XElement("Name", "Test2"), 
    new XElement("Type", "A")), 
    new XElement("Test", 
    new XElement("Name", "Test3"), 
    new XElement("Type", "B"))); 

string[] result = (from xe in root.Elements() 
        where xe.Element("Type").Value.Equals("A") 
        select xe.Element("Name").Value).ToArray(); 
相关问题