[英]Visual Studio c# / xml get specific sub-elements
Can someone help me with the best way to get specific sub-element values from an XML file using visual studio (c#). 有人可以使用Visual Studio(c#)帮助我以最佳方式从XML文件中获取特定的子元素值。 I am new to using XML never mind using it in visual studio.
我对使用XML是陌生的,没关系在Visual Studio中使用它。
Here is some example XML, I want to get "data_A" and "data_B" from level 1 only, for example, but at the same time, I would like to be able to reuse the code to do the same for level 2, without the need to rewrite everything. 这是一些示例XML,例如,我只想从级别1获取“ data_A”和“ data_B”,但是同时,我希望能够重用代码对级别2执行相同的操作,而无需需要重写一切。
<game name="test">
<area level="1">
<data_a> foo </data_a>
<data_b> foo </data_b>
<data_c> foo </data_c>
</area>
<area level="2">
<data_a> foo </data_a>
<data_b> foo </data_b>
<data_c> foo </data_c>
</area>
</game>
Also, sorry for the wall of spam. 另外,对垃圾邮件墙表示歉意。
Best is relative as famous mathematician Lewis Carroll said. 最好是相对的,正如著名数学家刘易斯·卡洛尔(Lewis Carroll)所说。 Try this xml linq solution:
试试这个xml linq解决方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var resuts = doc.Descendants("area").Where(x => (int)x.Attribute("level") == 1).Elements().Select(x => new {
name = x.Name.LocalName,
value = (string)x
}).ToList();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.