2

我有 XmlDocument Example.xml 的一部分,如下所示:

<rapaine dotoc="palin" domap="rattmin">
  <derif meet="local" />
  <derif meet="intro" />
.
.
.
</rapaine>

在这里,我正在创建一个节点列表并获取元素 raplin 以获取其属性。

现在我想确定属性“dotoc”和“domap”是否是 rapaine 的属性,其各自的值始终是固定的。然后只有我可以访问 childNodes 的“deriff”及其属性“meet”。这里的值只会改变。
我已经编写了一部分代码,没有编译错误,但在调试时我发现它没有进入 for 循环来检查它的属性和子节点。

XmlNodeList listOfSpineRootNodes = opfXmlDoc.GetElementsByTagName("rapine");
for (int x = 0; x < listOfSpineRootNodes.Count; x++)
  {
    XmlAttributeCollection spineAttributes = listOfSpineRootNodes[x].Attributes;
    string id = spineAttributes[0].Value;
    if (spineAttributes != null)
    {
      XmlNode attrToc = spineAttributes.GetNamedItem("dotoc");
      XmlNode attrPageMap = spineAttributes.GetNamedItem("domap");
      if (attrToc.Value == "palin" && attrPageMap.Value == "rattmine")
      {
        if (listOfSpineRootNodes != null)
        {
          foreach (XmlNode spineNodeRoot in listOfSpineRootNodes)
          {
            XmlNodeList listOfSpineItemNodes = spineNodeRoot.ChildNodes;
            if (listOfSpineItemNodes != null)
            {
              foreach (XmlNode spineItemNode in listOfSpineItemNodes)
              {
                if (spineItemNode.NodeType == XmlNodeType.Element
                  && spineItemNode.Name == "derif")
                {
                  XmlAttributeCollection spineItemAttributes = spineItemNode.Attributes;

                  if (spineItemAttributes != null)
                  {
                    XmlNode attrIdRef = spineItemAttributes.GetNamedItem("meet");
                    if (attrIdRef != null)
                    {
                      spineListOfSmilFiles.Add(attrIdRef.Value);
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

你能告诉我哪里出错了..谢谢....

4

3 回答 3

2

您可以使用 XPath 使用以下代码执行此操作。由于 XPath 是一种专门为查询 XML 文档而设计的语言,因此您应该考虑学习它。大多数新手喜欢在W3schools开始学习。

这是代码:

XmlNodeList meetList = opfXmlDoc.SelectNodes("/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet")
if (meetList.Count > 0)
{
  foreach (XmlNode meet in meetList)
  {
    spineListOfSmilFiles.Add(meet.Value);
  }
}

供您参考,XPath 表达式:

/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet

可以解释为:

a) 查找所有具有值为“palin”的属性和值为“rattmin”的属性的rapaine根级元素。dotocdomap

b) 在这些rapaine元素中,找到所有derif子元素。

c) 在这些derif元素中,检索所有meet属性。

请注意代码变得多么简洁。

于 2009-04-24T09:31:19.753 回答
0

你不能用一个简单的 XPath 表达式来解决这个问题吗?

所有带有条件的嵌套循环都只是自找麻烦。

于 2009-04-24T07:58:44.983 回答
0

根据您使用的 .NET 版本,LINQ 可能会简化这一点。

于 2009-04-24T08:16:20.073 回答