如果有多个具有相同名称的元素,如何使用GetElementsByTagName获取最后一个元素的innerText?

时间:2016-06-26 13:52:54

标签: c# xml

我有这个XML

<WordDefinition>
  <Word>analyses</Word>
  <Definitions>
    <Definition>
      <Word>analyses</Word>
      <Dictionary>
        <Id>wn</Id>
        <Name>WordNet (r) 2.0</Name>
      </Dictionary>
      <WordDefinition>analyses
         See {analysis}
      </WordDefinition>
    </Definition>
    <Definition>
      <Word>analyses</Word>
      <Dictionary>
        <Id>wn</Id>
        <Name>WordNet (r) 2.0</Name>
      </Dictionary>
      <WordDefinition>analysis
     n 1: an investigation of the component parts of a whole and their
          relations in making up the whole
      </WordDefinition>
    </Definition>
  </Definitions>
</WordDefinition>

我编写了这个C#来获取“WordDefinition”的innerText,如果只有一个“wordDefinition”就可以正常工作。但是,如果一个或多个,我想获取最后一个的innerText。

 var doc = new XmlDocument();
 doc.LoadXml(responseFromServer);
 var el = doc.GetElementsByTagName("WordDefinition");

有没有人有任何想法我怎么能这样做?对于这个例子,我想得到这个的innerText:

  <WordDefinition>analysis
 n 1: an investigation of the component parts of a whole and their
      relations in making up the whole
  </WordDefinition>

1 个答案:

答案 0 :(得分:1)

对不起VB ...使用XElement你可以得到像这样的最后一个WordDefinition

    Dim doc As XElement

    ' to load   doc = XElement.Load("path/URI here")
    ' for testing
    doc = <WordDefinition>
              <Word>analyses</Word>
              <Definitions>
                  <Definition>
                      <Word>analyses</Word>
                      <Dictionary>
                          <Id>wn</Id>
                          <Name>WordNet (r) 2.0</Name>
                      </Dictionary>
                      <WordDefinition>analyses
     See {analysis}
  </WordDefinition>
                  </Definition>
                  <Definition>
                      <Word>analyses</Word>
                      <Dictionary>
                          <Id>wn</Id>
                          <Name>WordNet (r) 2.0</Name>
                      </Dictionary>
                      <WordDefinition>analysis
 n 1: an investigation of the component parts of a whole and their
      relations in making up the whole
  </WordDefinition>
                  </Definition>
              </Definitions>
          </WordDefinition>

    'get the last WordDefinition
    Dim lastDef As XElement = doc...<WordDefinition>.LastOrDefault

如果没有测试数据,它将只是:

    Dim doc As XElement = XElement.Load("path/URI here")

    'get the last WordDefinition
    Dim lastDef As XElement = doc...<WordDefinition>.LastOrDefault

你可以做的其他一些事情......

所有定义

    Dim allDefs As IEnumerable(Of XElement) = doc...<WordDefinition>

粗滤器

    Dim whDef As String = "analys"
    Dim multiDef As IEnumerable(Of XElement) = From wd In doc...<WordDefinition>
                                                  Where wd.Value.Trim.StartsWith(whDef)
                                                  Select wd