我有以下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>
我想要做的是,如果HP类型是HP,请跳过HP计算机, anybode能告诉我怎么做吗?
我正在使用以下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"/>
有关如何跳过这些行的任何帮助? 谢谢。
答案 0 :(得分:1)
您可以使用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")
}
};
这将为您提供强类型匿名对象的集合,表示具有嵌套附件集合的计算机数据。
答案 1 :(得分:0)
实际上这没有用,因为我要根据数量过滤, 对不起,我已经在那里更新了代码,请你重新检查一下吗?
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?
按照这样的计数过滤?
答案 2 :(得分:0)
而不是检查hpCount&gt; 1,检查hpCount&gt; 0 强>
if(hpCount >1)
{
reader.Skip();
continue;
}