使用LINQ获取单个XML节点

时间:2011-08-25 07:10:15

标签: xml linq parsing

我有以下XML

<?xml version="1.0" encoding="utf-8"?>
<thesaurus>
    <wordblock>
        <term type="forbidden" lang="en" termid="27561">
            <value>710 REACTOR</value>
            <historynote>Prior to May 1993, this was a valid ETDE descriptor.</historynote>
        </term>
        <dates>
            <date type="created">2000-04-12</date>
            <date type="modified">2000-04-12</date>
        </dates>
        <terms>
            <term rel="SEE" lang="en" termid="3124" type="valid">
                <value>ENRICHED URANIUM REACTORS</value>
            </term>
            <term rel="SEE" lang="en" termid="3387" type="valid">
                <value>FAST REACTORS</value>
            </term>
            <term rel="SEE" lang="en" termid="3876" type="valid">
                <value>GAS COOLED REACTORS</value>
            </term>
            <term rel="SEE" lang="en" termid="6199" type="valid">
                <value>MOBILE REACTORS</value>
            </term>
            <term rel="SEE" lang="en" termid="7969" type="valid">
                <value>PROPULSION REACTORS</value>
            </term>
        </terms>
    </wordblock>
    <wordblock>
      [...]
      [...]
      [...]
   </wordblock>
</thesaurus>

我正在尝试使用LINQ解析XML并获取特定节点。在上面的例子中,我需要匹配值“710 REACTOR”,并在同一个<terms>节点内获得相应的<wordblock>节点。我对LINQ语法不太熟悉,所以非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

LINQ在这种情况下不会有用。那么使用XMLDocument呢?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load('your xml');
XmlNode node =  xmlDoc.SelectSingleNode("//WordBlock/term[value = '710 REACTOR']");

答案 1 :(得分:0)

尝试

XDocument xdoc = XDocument.Load(PATH_TO_YOUR_DOCUMENT);
var termNodes = from x in xdoc.Descendants("term") 
                where x.Element("value").Value == "710 REACTOR" 
                select x;