我有以下XML
<Company name="Kinanah Computers">
<Computer Name="Computer" type="Dell">
<Accessory type="screen" model="dell"/>
<Accessory type="mouse" model="dell"/>
<Accessory type="keyboard" model="dell"/>
</Computer>
<Computer Name="Computer" type="HP">
<Accessory type="screen" model="hp"/>
<Accessory type="mouse" model="chinese"/>
<Accessory type="keyboard" model="dell"/>
</Computer>
<Computer Name="Computer" type="HP">
<Accessory type="screen" model="hp"/>
<Accessory type="mouse" model="chinese"/>
<Accessory type="keyboard" model="dell"/>
</Computer>
<Computer Name="Computer" type="acer">
<Accessory type="screen" model="acer"/>
<Accessory type="mouse" model="acer"/>
<Accessory type="keyboard" model="acer"/>
</Computer>
</Company>我想做的是跳过惠普电脑,如果它的类型是惠普,谁能告诉我怎么做吗?
我使用了以下C#代码:
var stream = new StringReader(instanceXml/*the xml above*/);
var reader = XmlReader.Create(stream);
var hpCount = 0;
reader.MoveToContent();
while (reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
if(reader.GetAttribute("Name") == "Computer" && reader.GetAttribute("type") == "HP")
{
if(hpCount >1)
{
reader.Skip();
continue;
}
hpCount++;
}
}
}但是跳过不起作用,下一个被读取的元素是
<Accessory type="screen" model="hp"/>如何跳过这些行有什么帮助吗?谢谢。
发布于 2012-11-19 18:32:31
您可以使用Linq轻松解析您的xml:
XDocument xdoc = XDocument.Parse(instanceXml);
var query = from c in xdoc.Descendatns("Computer")
where (string)c.Attribute("type") != "HP"
select new {
Name = (string)c.Attribute("Name"),
Type = (string)c.Attribute("type"),
Accessories = from a in c.Elements()
select new {
Type = (string)a.Attribute("type"),
Model = (string)a.Attribute("model")
}
};这将为您提供强类型匿名对象的集合,用嵌套附件集合表示计算机数据。
发布于 2012-11-19 19:06:54
实际上这不会有什么帮助,因为我将根据计数进行过滤,对不起,我已经更新了上面的代码,你能重新检查一下吗?
List<XElement> query = from c in xdoc.Decendants("Computer") // from <Computer> tag or lower
where (string)c.Attribute("type") == "HP" // where <Computer> attribute name is "type" and "type" equals string value "HP"
select c; // return List of matching `<Computer>` XElements
int HpComputers = query.count; // You want to filter by amount of HP computers?像这样按计数过滤吗?
发布于 2012-11-19 19:14:15
不检查hpCount > 1,而是检查hpCount > 0
if(hpCount >1)
{
reader.Skip();
continue;
}https://stackoverflow.com/questions/13451883
复制相似问题