簡體   English   中英

從XML文檔(C#)的子節點提取InnerText失敗

[英]Unsuccessfully extracting InnerText from child nodes of XML document (C#)

我正在使用的XML如下:

<?xml version="1.0" encoding="utf-8"?><entry_list version="1.0"><entry 
id="commode"><ew>commode</ew><subj>HH-2#CL-1#FU-2a,b,c#BD-2d</subj><art>
<artref id="commode" /><capt>commode 1</capt><dim>54,18</dim></art>
<hw>com*mode</hw><sound><wav>commod01.wav</wav><wpr>ku-!mOd</wpr></sound>
<pr>kə-ˈmōd</pr><fl>noun</fl><et>French, from <it>commode,</it> adjective, 
suitable, convenient, from Latin <it>commodus,</it> from <it>com-</it> + 
<it>modus</it> measure <ma>mete</ma></et><def><date>circa 1688</date>
<sn>1</sn><dt>:a woman's ornate cap popular in the late 17th and early 18th 
centuries</dt><sn>2 a</sn><dt>:a low chest of drawers</dt><sn>b</sn><dt>:a 
movable washstand with a cupboard underneath</dt><sn>c</sn><dt>:a boxlike 
structure holding a chamber pot under an open seat</dt><sd>also</sd><dt>:
<sx>chamber pot</sx></dt><sn>d</sn><dt>:<sx>toilet <sxn>3b</sxn></sx></dt>
</def><art><bmp>commode.bmp</bmp><cap>commode 
1</cap></art></entry></entry_list> 

我正在使用的代碼,從各種相關問題中整理而成:

System.Xml.XmlNodeList elemList = doc.GetElementsByTagName("dt");
List<string> defs = new List<string>();

for (int count = 0; count < elemList.Count; count++)
{
    string contents = string.Empty;
    foreach (System.Xml.XmlNode child in elemList[count])
    {

        if (child.NodeType == System.Xml.XmlNodeType.Element)
        {
            contents += child.InnerText;
        }
    }
    defs.Insert(count, contents);
}

出於各種原因,生成的“ defs”列表為空,而我卻不知道所有這些原因。

這是使用LINQ。 elementName參數傳遞“ dt”。

static List<string> GetInnerText(XDocument xDoc, string elementName)
{
    var children = from node in xDoc.Descendants(elementName).DescendantNodes()
                   where node.NodeType == XmlNodeType.Text
                   select ((XText)node).Value;
    return children.ToList();
}

我不確定上面是否正是您想要的,所以這是一個替代解決方案。

static List<string> GetInnerText(XmlDocument xDoc, string elementName)
{
    List<string> innerText = new List<string>();
    var children = xDoc.GetElementsByTagName(elementName);
    foreach (XmlNode child in children)
        innerText.Add(child.InnerText);
    return innerText;
}

elemList = doc.GetElementsByTagName("dt"); 返回一個XmlNodeList。 您可以直接對此進行迭代。

將此System.Xml.XmlNode child in elemList[count]中的System.Xml.XmlNode child in elemList更改System.Xml.XmlNode child in elemList[count]中的System.Xml.XmlNode child in elemList並在調試器中查看child的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM