【问题标题】:Getting the root element of xml file in linq在linq中获取xml文件的根元素
【发布时间】:2016-01-16 15:01:44
【问题描述】:

我正在使用 linq。这是我的文档结构:

<t totalWord="2" creationDate="15.01.2016 02:33:37" ver="1">
    <k kel_id="1000">
        <kel>7</kel>
        <kel_gs>0</kel_gs>
        <kel_bs>0</kel_bs>
        <km>Ron/INT-0014</km>
        <kel_za>10.01.2016 02:28:05</kel_za>
        <k_det kel_nit="12" kel_res="4" KelSID="1" >
            <kel_ac>ac7</kel_ac>
        </k_det>
    </k>
    <k kel_id="1001">
        <kel>whitte down</kel>
        <kel_gs>0</kel_gs>
        <kel_bs>0</kel_bs>
        <km>Ron/INT-0014</km>
        <kel_za>15.01.2016 02:33:37</kel_za>
        <k_det kel_nit="12" kel_res="4" KelSID="1">
            <kel_ac>to gradually make something smaller by making it by taking parts away</kel_ac>
            <kel_kc>cut down</kel_kc>
            <kel_oc>The final key to success is to turn your interviewer into a champion: someone who is willing to go to bat for you when the hiring committee meets to whittle down the list.</kel_oc>
            <kel_trac >adım adım parçalamak</kel_trac>
        </k_det>
    </k>
</t>

这是一本字典。 t 是根。 k 是单词。当一个新词到达时,totalword 属性和 creationDate 应该相应地更新。我必须获取 t 节点,获取它的属性并保存它。上面的代码我已经写好了:

XDocument xdoc = XDocument.Load(fileName);
XElement rootElement = xdoc.Root;
XElement kokNode = rootElement.Element("t");
XAttribute toplamSayi = kokNode.Attribute("totalWord");

kokNode 为空。我该如何解决?提前致谢。

【问题讨论】:

  • 如果&lt;t&gt; 是根,只需设置var kokNode = xdoc.Root

标签: c# xml linq xelement


【解决方案1】:

xdoc.Root 将返回根元素,在本例中为您的 t 元素。

rootElement.Element("t") 因此将返回null,因为t 没有子t 元素。

使用xdoc.Rootxdoc.Element("t"),即:

var tomplamSayi = xdoc.Root.Attribute("totalWord")

或:

var tomplamSayi = xdoc.Element("t").Attribute("totalWord")

【讨论】:

    【解决方案2】:

    试试这个:

    string totalword;
    foreach (XElement x in xdoc.Descendants("t")){
       totalword= x.Attribute("totalword").Value.ToString().Trim(); // Get the totalword attribute's value
    }
    

    【讨论】:

    • 感谢三位的回答。由于我无法将多个答案设置为答案,因此我将最近的答案设置为答案。
    【解决方案3】:

    “totalWord”是根元素t 的属性,而不是k 的属性。所以只需像这样从根元素中获取属性:

    XDocument xdoc = XDocument.Load(fileName);
    
    XElement rootElement = xdoc.Root;
    
    XAttribute toplamSayi = rootElement.Attribute("totalWord");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多