【发布时间】:2017-12-06 06:58:25
【问题描述】:
我有一个具有以下结构的 XML 文件:
<root>
<body>
<e1>
<en>
<tag1>testt1</tag1>
<tag2 user="anonym">testt2</tag2>
<tag3>testt3</tag3>
<tag4>testt4</tag4>
<tag5>
<t51>tttt</t51>
<t52>ttt</t52>
<t53>ttt</t53>
</tag5>
</en>
<r1>1</r1>
<r2>
<tr1>0</tr1>
</r2>
</e1>
<r1>
</r1>
<r2>
</r2>
</body>
<info>
</info>
</root>
我需要将<e1> 元素中的数据放入某些变量中以供进一步使用。为此,我正在执行以下操作:
foreach (XElement elem in xmlDoc.Descendants("body").Descendants("e1"))
{
tag1 = elem.Element("en").Element("tag1").Value;
tag2 = elem.Element("en").Element("tag2").Value;
tag2a = elem.Element("en").Element("tag2").Attribute("user").Value;
tag3 = elem.Element("en").Element("tag3").Value;
tag4 = elem.Element("en").Element("tag4").Value;
t51 = elem.Element("en").Element("tag5").Element("t51").Value;
t52 = elem.Element("en").Element("tag5").Element("t52").Value;
t53 = elem.Element("en").Element("tag5").Element("t53").Value;
r1 = elem.Element("r1").Value;
tr1 = elem.Element("r2").Element("tr1").Value;
}
它工作正常,但我认为,这看起来不是最好的方法。我是XDocuments 的新手,在C# 中与XML 合作。很好奇,是否有更好的方法来做到这一点?
【问题讨论】:
-
嗨,给你的代码更新了我的答案,你能看看,这是有效的做事方式
标签: c# xml xml-parsing