【问题标题】:how to select a node from xml file?如何从 xml 文件中选择一个节点?
【发布时间】:2012-01-11 22:00:48
【问题描述】:

下面是我的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>

<book category="cooking">
<book>
    <bookID>1111</bookID>
</book>
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<book>
    <bookID>54655</bookID>
</book>
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<book>
    <bookID>5556</bookID>
</book>
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="web" cover="paperback">
<book>
    <bookID>1111</bookID>
</book>
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>

我需要显示书籍的“标题”。

下面是我用来显示数据的asp代码

<%
'' #Load XML

Set xml= Server.CreateObject("Msxml2.DOMDocument.3.0")
    xml.async = False
    xml.load (Server.MapPath("test.xml"))

    if xml.parseError.errorcode<>0 then
    response.write   "error handling code" &xml.parseError.errorcode
    else

        Set objLst= xml.getElementsByTagName("bookstore").item(0).getElementsByTagName("book")
        TotalBooks = (objLst.Length)-1
        For i=0 to eval(TotalBooks)
            response.write xml.getElementsByTagName("bookstore").item(0).getElementsByTagName("book").item(i).getElementsByTagName("title").item(0).text&"<br/>"
        Next

    end if

%>

但是“objLst.length”显示了&lt;book&gt;的子节点

在这个原因我得到错误

代码只显示第一个节点书名。它不会进入第二个节点。怎么修?

i need out put like below

Everyday Italian

Harry Potter

XQuery Kick Start

Learning XML

【问题讨论】:

    标签: xml asp-classic


    【解决方案1】:

    如果您不能按照@sonjz 的建议使用 System.Xml.Linq,那么您可以使用 SelectNodes 和 XPath 表达式

    set nodes = xml.documentElement.selectNodes("//book/title")
    
    for each node in nodes
        response.write node.text & "<br/>"
    next
    

    【讨论】:

      【解决方案2】:

      使用 System.Xml.Linq,这将是最简单的。

      将其加载到 XElement 中并使用 Linq 进行查询。

      XDocument test = XDocument.Load(xmlFilename); // load from string if you want
      XElement cooking = test.Element("bookstore")
                             .Descendants("book")
                             .Where(e => e.Attribute("category" => "cooking")
                             .FirstOrDefault();
      

      【讨论】:

      • -1 这是一个 ASP-Classic 问题,XDocument/Linq 不可用。
      • 请注意,我记得 XPath 有一件奇怪的事情,selectNodes(获取列表)和 selectSingleNode(第一次出现)xml.documentElement.selectSingleNode("//book[category='cooking']")
      猜你喜欢
      • 2012-04-10
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多