0

我有以下 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,有谁能告诉我该怎么做吗?

我正在使用以下 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++;
     }
  }
}

但是 Skip 不起作用,读取的下一个元素是

<Accessory type="screen" model="hp"/>

关于如何跳过这些行的任何帮助?谢谢你。

4

3 回答 3

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")
                             }
            };

这将为您提供强类型匿名对象的集合,用嵌套的附件集合表示计算机数据。

于 2012-11-19T10:32:30.573 回答
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?

像这样根据计数过滤?

于 2012-11-19T11:06:53.767 回答
0

不是检查 hpCount > 1,而是检查 hpCount > 0

if(hpCount >1)
{
  reader.Skip();
  continue;
 }
于 2012-11-19T11:14:14.507 回答