当 XML 中的节点内容为空时,无法拆分该节点的内容

发布于 2024-12-11 07:42:48 字数 4469 浏览 0 评论 0原文

给出以下 XML 我试图通过 | 将“额外”节点的内容分成四个部分分隔符并返回响应中的四个部分作为 chdspt(0)、chdspt(1)、chdspt(2) 和 chdspt(3)。我似乎遇到的问题是,如果加载的 XML 缺少“额外”节点内的任何内容,则整个脚本将失败并出现 500 错误。

<Export>
    <SAVED_EXPORT>
        <id>00-6189</id>
        <title>00-6189 Start Mech Switch</title>
        <price>5.46 USD</price>
        <extra>Male|Adult|Black|medium</extra>
    </SAVED_EXPORT>
    <SAVED_EXPORT>
        <id>00-6190</id>
        <title>00-6190 Start Mech Switch</title>
        <price>5.46 USD</price>
        <extra></extra>
    </SAVED_EXPORT>
</Export>

请注意,我从上面的 XML 中删除了许多同级节点,因为发布的内容太多,并且对于当前的问题来说应该是不必要的。

Dim xData,xNewDoc,xmldataout,xmldataout2,title,description,link,gpc,chd,chdspt

url = "http://thesite.com/v/myxml.xml"
Set xData = Server.CreateObject("Microsoft.XMLHTTP")
xData.Open "get", url, False
xData.Send
Set xNewDoc = xData.responseXML 'ResponseXml returns DOMDocument object

For Each x In xNewDoc.documentElement.selectNodes(".//SAVED_EXPORT")

    Dim productid: Set productid = x.selectSingleNode("id")
    Dim pt: Set pt = x.selectSingleNode("title")
    Dim pds: Set pds = x.selectSingleNode("striphtml-description")
    Dim pl: Set pl = x.selectSingleNode("link")
    Dim pe: Set pe = x.selectSingleNode("product_type")
    Dim pri: Set pri = x.selectSingleNode("price")
    Dim psp: Set psp = x.selectSingleNode("sale_price")
    Dim pbr: Set pbr = x.selectSingleNode("brand")
    Dim pcn: Set pcn = x.selectSingleNode("condition")
    Dim pex: Set pex = x.selectSingleNode("expiration_date")
    Dim pwe: Set pwe = x.selectSingleNode("weight")
    Dim ppn: Set ppn = x.selectSingleNode("id")
    Dim pil: Set pil = x.selectSingleNode("image_link")
    Dim pav: Set pav = x.selectSingleNode("availability")
    Dim ppi: Set ppi = x.selectSingleNode("upc")
    Dim pch: Set pch = x.selectSingleNode("extra")

    title=Replace(pt.text,"&","&amp;")
    title=Replace(title,"<","&lt;")
    title=Replace(title,">","&gt;")

    description=Replace(pds.text,"&","&amp;")
    description=Replace(description,"<","&lt;")
    description=Replace(description,">","&gt;")

    link=Replace(pl.text,"&","&amp;")
    link=Replace(link,"<","&lt;")
    link=Replace(link,">","&gt;")

    gpc=Replace(pri.text,"&","&amp;")
    gpc=Replace(gpc,"<","&lt;")
    gpc=Replace(gpc,">","&gt;")

    chd = pch.text
    chdspt = split(chd, "|")    


xmldataout= "<item><g:id>" & productid.text & "</g:id>" & "<title>" & title & "</title>"
& "<description>" & description & "</description>" & "<link>" & link & "</link>"
& "<g:google_product_category>" & gpc & "</g:google_product_category>" & "<g:price>" & pri.text & "</g:price>" & "<g:sale_price>" & psp.text & "</g:sale_price>"
& "<g:brand>" & pbr.text & "</g:brand>" & "<g:condition>" & pcn.text & "</g:condition>"
& "<g:expiration_date>" & pex.text & "</g:expiration_date>" & "<g:shipping_weight>" & pwe.text & "</g:shipping_weight>" & "<g:mpn>" & ppn.text & "</g:mpn>"
& "<g:image_link>" & pil.text & "</g:image_link>" & "<g:availability>" & pav.text & "</g:availability>" & "<g:gtin>" & ppi.text & "</g:gtin>"
& "<g:gender>" & chdspt(0) &  "</g:gender>" & "<g:age_group>" & chdspt(1) & "</g:age_group>" & "<g:color>" & chdspt(2) & "</g:color>"
& "<g:size>" & chdspt(3) & "</g:size>  </item>" 

xmldataout2=xmldataout2+xmldataout
Next


Response.ContentType = "text/xml"
Response.Write("<?xml version='1.0' encoding='UTF-8'?><rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description>" & xmldataout2 & "</channel></rss>")

Set xNewDoc = Nothing
Set xData = Nothing

Give the following XML I am trying to split the contents of the "extra" node into four parts by the | delimiter and return the four parts in the response as chdspt(0), chdspt(1), chdspt(2) and chdspt(3). The problem I seem to have is if the XML loaded is missing anything inside the "extra" node then the whole script fails with a 500 error.

<Export>
    <SAVED_EXPORT>
        <id>00-6189</id>
        <title>00-6189 Start Mech Switch</title>
        <price>5.46 USD</price>
        <extra>Male|Adult|Black|medium</extra>
    </SAVED_EXPORT>
    <SAVED_EXPORT>
        <id>00-6190</id>
        <title>00-6190 Start Mech Switch</title>
        <price>5.46 USD</price>
        <extra></extra>
    </SAVED_EXPORT>
</Export>

Note that I removed a lot of the sibling nodes from the XML above as it is too much to post and should be unnecessary for the question at hand.

Dim xData,xNewDoc,xmldataout,xmldataout2,title,description,link,gpc,chd,chdspt

url = "http://thesite.com/v/myxml.xml"
Set xData = Server.CreateObject("Microsoft.XMLHTTP")
xData.Open "get", url, False
xData.Send
Set xNewDoc = xData.responseXML 'ResponseXml returns DOMDocument object

For Each x In xNewDoc.documentElement.selectNodes(".//SAVED_EXPORT")

    Dim productid: Set productid = x.selectSingleNode("id")
    Dim pt: Set pt = x.selectSingleNode("title")
    Dim pds: Set pds = x.selectSingleNode("striphtml-description")
    Dim pl: Set pl = x.selectSingleNode("link")
    Dim pe: Set pe = x.selectSingleNode("product_type")
    Dim pri: Set pri = x.selectSingleNode("price")
    Dim psp: Set psp = x.selectSingleNode("sale_price")
    Dim pbr: Set pbr = x.selectSingleNode("brand")
    Dim pcn: Set pcn = x.selectSingleNode("condition")
    Dim pex: Set pex = x.selectSingleNode("expiration_date")
    Dim pwe: Set pwe = x.selectSingleNode("weight")
    Dim ppn: Set ppn = x.selectSingleNode("id")
    Dim pil: Set pil = x.selectSingleNode("image_link")
    Dim pav: Set pav = x.selectSingleNode("availability")
    Dim ppi: Set ppi = x.selectSingleNode("upc")
    Dim pch: Set pch = x.selectSingleNode("extra")

    title=Replace(pt.text,"&","&")
    title=Replace(title,"<","<")
    title=Replace(title,">",">")

    description=Replace(pds.text,"&","&")
    description=Replace(description,"<","<")
    description=Replace(description,">",">")

    link=Replace(pl.text,"&","&")
    link=Replace(link,"<","<")
    link=Replace(link,">",">")

    gpc=Replace(pri.text,"&","&")
    gpc=Replace(gpc,"<","<")
    gpc=Replace(gpc,">",">")

    chd = pch.text
    chdspt = split(chd, "|")    


xmldataout= "<item><g:id>" & productid.text & "</g:id>" & "<title>" & title & "</title>"
& "<description>" & description & "</description>" & "<link>" & link & "</link>"
& "<g:google_product_category>" & gpc & "</g:google_product_category>" & "<g:price>" & pri.text & "</g:price>" & "<g:sale_price>" & psp.text & "</g:sale_price>"
& "<g:brand>" & pbr.text & "</g:brand>" & "<g:condition>" & pcn.text & "</g:condition>"
& "<g:expiration_date>" & pex.text & "</g:expiration_date>" & "<g:shipping_weight>" & pwe.text & "</g:shipping_weight>" & "<g:mpn>" & ppn.text & "</g:mpn>"
& "<g:image_link>" & pil.text & "</g:image_link>" & "<g:availability>" & pav.text & "</g:availability>" & "<g:gtin>" & ppi.text & "</g:gtin>"
& "<g:gender>" & chdspt(0) &  "</g:gender>" & "<g:age_group>" & chdspt(1) & "</g:age_group>" & "<g:color>" & chdspt(2) & "</g:color>"
& "<g:size>" & chdspt(3) & "</g:size>  </item>" 

xmldataout2=xmldataout2+xmldataout
Next


Response.ContentType = "text/xml"
Response.Write("<?xml version='1.0' encoding='UTF-8'?><rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description>" & xmldataout2 & "</channel></rss>")

Set xNewDoc = Nothing
Set xData = Nothing

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红墙和绿瓦 2024-12-18 07:42:48

这是代码的全新版本,使用“最佳实践”(即没有手动字符转义,没有从字符串构建 XML,而是使用 DOM,使用当前的 COM 对象(Microsoft.XMLHTTP 是这样的) 请注意,

NewElem()GetText() 是在代码末尾找到的便利函数,

  • 它们创建了一个新的 。带或不带命名空间的元素并添加 GetText()在上下文
  • (文档或节点)中搜索 XPath 表达式,并返回找到的第一个元素的文本值,或 ""(即更聪明的 .selectSingleNode())

ASP 代码:

Option Explicit

Const NODE_ELEMENT = 1

Dim Namespaces, XmlHttpReq, InputDoc, OutputDoc, Channel, x, NewItem
Dim url, StubFeed, v, vGender, vAgeGroup, vColor, vSize

url = "http://thesite.com/v/myxml.xml"
StubFeed = "<rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description></channel></rss>" 

' prepare a dictitionary of namespace prefixes and respective URIs
Set Namespaces = Server.CreateObject("Scripting.Dictionary")
Namespaces.Add "g", "http://base.google.com/ns/1.0"

Set OutputDoc  = Server.CreateObject("MSXML2.DOMDocument.4.0")
Set XmlHttpReq = Server.CreateObject("MSXML2.XMLHTTP.4.0")

' retrieve the source document
' TODO: Error handling in case the HTTP request fails!
XmlHttpReq.Open "GET", url, False
XmlHttpReq.Send
Set InputDoc = XmlHttpReq.responseXML

' the stub of the output is loaded from string
OutputDoc.loadXML StubFeed

' all new items are appended to this element
Set Channel = OutputDoc.selectSingleNode("/rss/channel")

For Each x In InputDoc.selectNodes("//SAVED_EXPORT")
  Set NewItem = OutputDoc.createElement("item")
  With NewItem
    .appendChild NewElem("g:id",                      GetText(x, "id"))
    .appendChild NewElem("title",                     GetText(x, "title"))
    .appendChild NewElem("description",               GetText(x, "striphtml-description"))
    .appendChild NewElem("link",                      GetText(x, "link"))
    .appendChild NewElem("g:google_product_category", GetText(x, "product_type"))
    .appendChild NewElem("g:price",                   GetText(x, "price"))
    .appendChild NewElem("g:sale_price",              GetText(x, "sale_price"))
    .appendChild NewElem("g:brand",                   GetText(x, "brand"))
    .appendChild NewElem("g:condition",               GetText(x, "condition"))
    .appendChild NewElem("g:expiration_date",         GetText(x, "expiration_date"))
    .appendChild NewElem("g:shipping_weight",         GetText(x, "weight"))
    .appendChild NewElem("g:mpn",                     GetText(x, "id"))
    .appendChild NewElem("g:image_link",              GetText(x, "image_link"))
    .appendChild NewElem("g:availability",            GetText(x, "availability"))
    .appendChild NewElem("g:gtin",                    GetText(x, "upc"))

    v = Split(Trim( GetText(x, "extra[normalize-space() != '']") ), "|")
    If UBound(v) = 3 Then
      vGender = v(0) : vAgeGroup = v(1) : vColor = v(2) : vSize = v(3)
    Else
      vGender = ""   : vAgeGroup = ""   : vColor = ""   : vSize = ""
    End If

    .appendChild NewElem("g:gender",    vGender)
    .appendChild NewElem("g:age_group", vAgeGroup)
    .appendChild NewElem("g:color",     vColor)
    .appendChild NewElem("g:size",      vSize)
  End With

  Channel.appendChild NewItem
Next

' send the feed (saving the document to the Response object does this)
Response.ContentType = "text/xml; charset=UTF-8"
OutputDoc.save Response

' --- HELPER FUNCTIONS ------------------------------------------------------
Function NewElem(name, text)
  Dim namespaceURI
  If InStr(name, ":") Then
    namespaceURI = Namespaces( Split(name, ":")(0) )
    Set NewElem = OutputDoc.createNode(NODE_ELEMENT, name, namespaceURI)
  Else
    Set NewElem = OutputDoc.createElement(name)
  End If

  If text <> "" Then NewElem.text = text
End Function

Function GetText(context, xPath)
  Dim node
  Set node = context.selectSingleNode(xPath)
  If node Is Nothing Then
    GetText = ""
  Else
    GetText = node.text
  End If
End Function

考虑使用更合适的 application/rss+xml 内容类型而不是 text/xml

Here is a completely new version of your code, using "best practices" (i.e. no manual character escaping, no building XML from strings but using a DOM instead, using current COM objects (Microsoft.XMLHTTP is way outdated).

Note that NewElem() and GetText() are convenience functions found at the end of the code.

  • NewElem() creates a new Element with or without namespace and adds a text value to it
  • GetText() searches a context (document or node) for an XPath expression and returns the text value of the first element found, or ""(i.e. a smarter .selectSingleNode())

ASP code:

Option Explicit

Const NODE_ELEMENT = 1

Dim Namespaces, XmlHttpReq, InputDoc, OutputDoc, Channel, x, NewItem
Dim url, StubFeed, v, vGender, vAgeGroup, vColor, vSize

url = "http://thesite.com/v/myxml.xml"
StubFeed = "<rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description></channel></rss>" 

' prepare a dictitionary of namespace prefixes and respective URIs
Set Namespaces = Server.CreateObject("Scripting.Dictionary")
Namespaces.Add "g", "http://base.google.com/ns/1.0"

Set OutputDoc  = Server.CreateObject("MSXML2.DOMDocument.4.0")
Set XmlHttpReq = Server.CreateObject("MSXML2.XMLHTTP.4.0")

' retrieve the source document
' TODO: Error handling in case the HTTP request fails!
XmlHttpReq.Open "GET", url, False
XmlHttpReq.Send
Set InputDoc = XmlHttpReq.responseXML

' the stub of the output is loaded from string
OutputDoc.loadXML StubFeed

' all new items are appended to this element
Set Channel = OutputDoc.selectSingleNode("/rss/channel")

For Each x In InputDoc.selectNodes("//SAVED_EXPORT")
  Set NewItem = OutputDoc.createElement("item")
  With NewItem
    .appendChild NewElem("g:id",                      GetText(x, "id"))
    .appendChild NewElem("title",                     GetText(x, "title"))
    .appendChild NewElem("description",               GetText(x, "striphtml-description"))
    .appendChild NewElem("link",                      GetText(x, "link"))
    .appendChild NewElem("g:google_product_category", GetText(x, "product_type"))
    .appendChild NewElem("g:price",                   GetText(x, "price"))
    .appendChild NewElem("g:sale_price",              GetText(x, "sale_price"))
    .appendChild NewElem("g:brand",                   GetText(x, "brand"))
    .appendChild NewElem("g:condition",               GetText(x, "condition"))
    .appendChild NewElem("g:expiration_date",         GetText(x, "expiration_date"))
    .appendChild NewElem("g:shipping_weight",         GetText(x, "weight"))
    .appendChild NewElem("g:mpn",                     GetText(x, "id"))
    .appendChild NewElem("g:image_link",              GetText(x, "image_link"))
    .appendChild NewElem("g:availability",            GetText(x, "availability"))
    .appendChild NewElem("g:gtin",                    GetText(x, "upc"))

    v = Split(Trim( GetText(x, "extra[normalize-space() != '']") ), "|")
    If UBound(v) = 3 Then
      vGender = v(0) : vAgeGroup = v(1) : vColor = v(2) : vSize = v(3)
    Else
      vGender = ""   : vAgeGroup = ""   : vColor = ""   : vSize = ""
    End If

    .appendChild NewElem("g:gender",    vGender)
    .appendChild NewElem("g:age_group", vAgeGroup)
    .appendChild NewElem("g:color",     vColor)
    .appendChild NewElem("g:size",      vSize)
  End With

  Channel.appendChild NewItem
Next

' send the feed (saving the document to the Response object does this)
Response.ContentType = "text/xml; charset=UTF-8"
OutputDoc.save Response

' --- HELPER FUNCTIONS ------------------------------------------------------
Function NewElem(name, text)
  Dim namespaceURI
  If InStr(name, ":") Then
    namespaceURI = Namespaces( Split(name, ":")(0) )
    Set NewElem = OutputDoc.createNode(NODE_ELEMENT, name, namespaceURI)
  Else
    Set NewElem = OutputDoc.createElement(name)
  End If

  If text <> "" Then NewElem.text = text
End Function

Function GetText(context, xPath)
  Dim node
  Set node = context.selectSingleNode(xPath)
  If node Is Nothing Then
    GetText = ""
  Else
    GetText = node.text
  End If
End Function

Think about using the more appropriate application/rss+xml content type instead of text/xml

凝望流年 2024-12-18 07:42:48

刚刚注意到@TomaLak 在上面这行代码中遗漏了

StubFeed = "<rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description></channel></rss>"

Just noticed that @TomaLak left out the <?xml version='1.0' ?> in this line of code above

StubFeed = "<rss version='2.0' xmlns:g='http://base.google.com/ns/1.0'><channel><title>store</title><link>http://www.thesite.com</link><description>This is a sample feed</description></channel></rss>"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文