11

这似乎不应该是困难的,但我目前被卡住了。我正在尝试从与给定 XPath 查询字符串匹配的节点中获取特定属性的属性值。这是我到目前为止所拥有的:

    public static IEnumerable<string> GetAttributes(this XmlDocument xml,
        string xpathQuery, string attributeName)
    {
        var doc = new XPathDocument(new XmlNodeReader(xml));
        XPathNavigator nav = doc.CreateNavigator();
        XPathExpression expr = nav.Compile(xpathQuery);
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            XPathNavigator curNav = iterator.Current;
            if (curNav.HasAttributes)
            {
                XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
                if (null != curNode)
                {
                    XmlAttribute attrib = curNode.Attributes[attributeName];
                    if (null != attrib)
                    {
                        yield return attrib.Value;
                    }
                }
            }
        }
    }

这当前会引发异常:

System.InvalidCastException:无法将“MS.Internal.Xml.Cache.XPathDocumentNavigator”类型的对象转换为“System.Xml.IHasXmlNode”类型。

我要解决这个问题了吗?有没有更简单的方法从匹配节点获取属性值?

4

3 回答 3

33

对于以下 xml:

<root>
  <elem att='the value' />
</root>

您可以使用此 C# 代码获取“值”文本

    XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(text);
    Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);
于 2010-11-29T21:20:01.017 回答
5

如果您使用的是 .net 3.5 或更高版本,则可以使用 linq to Xml

对于给定的 xml 文档

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <storedProcedures>
    <storedProcedure name="usp_GET_HOME_PAGE_DATA">
      <resultSet name="Features"/>
      <resultSet name="Highlights"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_FEATURES" />
    <storedProcedure name="usp_GET_FEATURE" />
    <storedProcedure name="usp_UPDATE_FEATURE" />
    <storedProcedure name="usp_GET_FEATURE_FOR_DISPLAY">
      <resultSet name="CurrentFeature"/>
      <resultSet name="OtherFeatures"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_HIGHLIGHT_TITLES">
      <resultSet name="Highlights"/>
    </storedProcedure>
  </storedProcedures>
</root>

The following linq expression will get you the values of the "name" attributes of all storedProcedure node

XDocument xDcoument = XDocument.Load(xmlStoredProcSchemeFile);

  var storedProcedureNames = from doc in xDcoument.Descendants("storedProcedure")
                             select doc.Attribute("name").Value;

you could also use regular XPath syntax. In the code below the variable node holds the node identified by the "usp_GET_HOME_PAGE_DATA" name and then the attributes variable holds all child nodes (the attributes) of the selected node and it's children.

  XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(@"C:\inetpub\wwwroot\ASPNETBuilder\BusinessLayer\DataAccessCodeGenerationSchema.xml");
  var node = xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGE_DATA']");
  var attributes = node.SelectNodes("./resultSet/@name");
于 2010-11-29T21:25:36.893 回答
1

solution to the initial problem of the exception being thrown...

var doc = new XPathDocument(new XmlNodeReader(xml));

should be replaced by...

var doc = new XmlDocument();
doc.load(*you can either specify the path to the file, the string out of which the xml document is to be generated or specify an xmlreader, look for more overloads*);

This will not throw the exception and the code will work just fine.

于 2011-01-17T07:40:40.593 回答