我正在使用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 是root。 k 是单词。当新单词到达时, totalword 属性和 creationDate 将相应更新。我必须得到 t 节点,获取其属性并保存它。我写了上面的代码:
XDocument xdoc = XDocument.Load(fileName);
XElement rootElement = xdoc.Root;
XElement kokNode = rootElement.Element("t");
XAttribute toplamSayi = kokNode.Attribute("totalWord");
kokNode 为空。我该如何解决?提前致谢。
答案 0 :(得分:1)
xdoc.Root
将返回根元素,在这种情况下,这是您的t
元素。
rootElement.Element("t")
将返回null
,因为t
没有子t
元素。
使用xdoc.Root
或xdoc.Element("t")
,即:
var tomplamSayi = xdoc.Root.Attribute("totalWord")
或:
var tomplamSayi = xdoc.Element("t").Attribute("totalWord")
答案 1 :(得分:0)
试试这个:
string totalword;
foreach (XElement x in xdoc.Descendants("t")){
totalword= x.Attribute("totalword").Value.ToString().Trim(); // Get the totalword attribute's value
}
答案 2 :(得分:0)
“totalWord”是根元素的属性,t
,而不是k
的属性。所以只需从根元素中获取属性,如下所示:
XDocument xdoc = XDocument.Load(fileName);
XElement rootElement = xdoc.Root;
XAttribute toplamSayi = rootElement.Attribute("totalWord");