2012-01-11 66 views
1

下面是我的XML文件如何從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」表示本因爲我得到錯誤

代碼顯示的<book>

子節點僅拳頭節點書名只。它不會去第二個節點。我是否修復它?

i need out put like below 

Everyday Italian 

Harry Potter 

XQuery Kick Start 

Learning XML 

回答

-1

使用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(); 
+0

-1這是一個ASP-經典問題的XDocument/Linq的不可用。 – AnthonyWJones 2012-01-12 14:41:10

+0

對不起錯過了,@CCBlackburn的應該做的伎倆。 – sonjz 2012-01-12 15:43:51

+0

請注意,我記得有一件奇怪的事情用XPath, selectNodes(獲取列表)和selectSingleNode(第一次出現) xml.documentElement.selectSingleNode(「// book [category ='cooking']」) – sonjz 2012-01-12 15:50:12

2

如果您不能使用System.Xml.Linq的作爲@sonjz那麼建議你可以使用SelectNodes和XPath表達式

set nodes = xml.documentElement.selectNodes("//book/title") 

for each node in nodes 
    response.write node.text & "<br/>" 
next