Parsing XML with ASP

2019-09-15 09:30发布

问题:

I have the code below, I just need help on figuring out the best way to get html from the content node below instead of plaintext. Any help is much appreciated.

sKey = objItem.GetAttribute("id")             
Title = objItem.selectSingleNode("title").text
Blurb = objItem.selectSingleNode("blurb").text
Content = objItem.selectSingleNode("content").text
Image = objItem.selectSingleNode("image").text
myDate = objItem.selectSingleNode("date").text
myMonth = objItem.selectSingleNode("month").text

回答1:

In my experience the best way of handling XML with Classic ASP is to use an XSL stylesheet.

XSLT is quite easy to learn at a basic level, although the learning curve gets a bit steeper later on.

I recommend the w3schools tutorial

http://www.w3schools.com/xsl/

Once you've written your stylesheet, if you have a local XML source your asp code would look like this

set xml = Server.CreateObject("Msxml2.DomDocument")
xml.load(Server.Mappath("source.xml"))
set xsl = Server.CreateObject("Msxml2.DomDocument")
xsl.load(Server.Mappath("stylesheet.xsl"))
Response.Write(xml.transformNode(xsl))
set xsl = nothing
set xml = nothing

If the xml is from a remote url then it's a little more complex

set xml = Server.CreateObject("Msxml2.DomDocument")
xml.setProperty "ServerHTTPRequest", true
xml.async = false
xml.validateOnParse = false
xml.load("http://xmlsource.com")
set xsl = Server.CreateObject("Msxml2.DomDocument")
xsl.load(Server.Mappath("stylesheet.xsl"))
Response.Write(xml.transformNode(xsl))
set xsl = nothing
set xml = nothing

Edit

<h2><%= Title %></h2>


回答2:

You can get the XML of a node using the xml property instead of the text property you are using now:

    dim o_xml, o_node
    set o_xml = Server.CreateObject("Msxml2.DomDocument")
    o_xml.load("books.xml")
    set o_node = o_xml.selectSingleNode("//catalog/book[@id='bk102']")
    Response.Write Server.htmlEncode(o_node.xml)

Docs here: http://msdn.microsoft.com/en-us/library/ms755989%28v=vs.85%29.aspx