我需要解析一个xml文件,需要加入节点’driver’的结果.每个’品牌’节点都是唯一的.样本xml文件:
<brand name = "ford">
<transport category="car">
<driver name="John, Doe"/>
<driver name="Jane, Doe"/>
</transport>
</brand>
<brand name = "opel">
<transport category="car">
<driver name="Jerry, Smith"/>
<driver name="Jeff, Perry"/>
</transport>
</brand>
预期结果:
John, Doe - Jane, Doe
Jerry, Smith - Jeff, Perry
我的代码到目前为止:
XmlTextReader reader = new XmlTextReader(@"D:\myfile.xml");
while (reader.Read())
{
if (reader.Name == "brand")
{
XmlReader inner = reader.ReadSubtree();
while (inner.Read()) ;
if (reader.Name == "driver")
{
string drvNames = reader.GetAttribute("name");
}
}
}
我无法得到’司机’的结果.有一个或多个’驱动’节点.语言C#
解决方法:
你可以使用Linq到Xml:
var xdoc = XDocument.Load(@"D:\myfile.xml");
var query = from t in xdoc.Descendants("transport")
select String.Join(" - ", t.Elements("driver")
.Select(e => (string)e.Attribute("name")));
如果无法将整个文件加载到内存中:
XmlTextReader reader = new XmlTextReader(@"D:\myfile.xml");
List<string> result = new List<string>();
while (reader.Read())
{
if (reader.Name == "brand")
{
XmlReader inner = reader.ReadSubtree();
List<string> names = new List<string>();
while (inner.Read())
{
if (reader.Name == "driver")
names.Add(reader.GetAttribute("name"));
}
if (names.Any())
result.Add(String.Join(" - ", names));
}
}