我可以在javascript中使用XPath返回整个XML文档吗?

时间:2010-11-03 06:08:54

标签: javascript xslt xpath xquery xmldom

我正在使用Javascript,我想返回一个包含我想要的结果的XML文档。

例如,XML文档可以是 <books> <book> <title> Introduction to XML </title> </book> <book> <title> Introduction to Javascript </title> </book> </books>

并使用此XPath表达式: //book[./title="Introduction to XML"]我想得到一份这样的文件 <books> <book> <title> Introduction to XML </title> </book> </books>

我知道XQuery听起来像是这里的解决方案,但我使用的是Javascript,据我所知,在Javascript中没有内置的XQuery实现。

我想把祖先和我需要的东西一起归还。但是如果我得到几个结果它也应该有效..这是否可以使用XPath?

3 个答案:

答案 0 :(得分:2)

XPath无法更改源XML文档,也无法生成新的XML文档。

因此,必须使用其他一些技术。 XSLT是一种专门用于表达此类转换的语言。

在大多数浏览器中,您可以使用通过关联<?xml-stylesheet ?> PI(processong指令)标识的XSLT样式表处理XML文档。

大多数浏览器还提供了一些在Javascript中启动XSLT转换的方法 - 阅读浏览器文档。

XSLT转换本身非常简单:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pTitleWanted" select="' Introduction to XML '"/>

 <xsl:template match="node()|@*" name="identity">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="books">
  <xsl:copy>
    <xsl:apply-templates select="book[title = $pTitleWanted]"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于提供的XML文档

<books>
    <book>
        <title> Introduction to XML </title>
    </book>
    <book>
        <title> Introduction to Javascript </title>
    </book>
</books>

产生了想要的正确结果

<books>
   <book>
      <title> Introduction to XML </title>
   </book>
</books>

答案 1 :(得分:0)

浏览器JavaScript环境附带默认的Xml文档对象模型分析器。

您可以利用该控件并将其解析为Dom Parsing Style。

enter code here
var _xml = "<books> <book> <title> Introduction to XML </title> </book> </books>"
parser=new DOMParser();
xmlDoc=parser.parseFromString(_xml,"text/xml");
//Use any type of DOM API to parse
xmlDoc.childNodes()...... 

This code is for FireFox Browser. You can do the same thing in IE using their ActiveXControls as like XmlHttp way.

答案 2 :(得分:0)

一般情况下,你不能单独使用XPath - 它只是一种表达式语言。 XPath无法创建只能选择它们的节点。您可以(如您所样)选择一组节点,但不能将它们包装在其他节点中。

你当然可以改变@ kadalmittai的建议并使用DOM API来选择你的节点,创建一个新文档并将你选择的节点克隆到它中,但鉴于你的相当简单的要求,这是相当重要的。

XSLT可能是一种更好的方法,但我不太了解浏览器技术,告诉你如何在浏览器中使用它。

相关问题