我正在使用 Javascript,并且我想返回一个包含我想要的结果的 XML 文档。
例如,XML 文档可以是
<代码>
<书籍>
<书>
<标题>
XML简介
<书>
<标题>
JavaScript 简介
并使用此 XPath 表达式:
//book[./title="Introduction to XML"]
我想得到这样的文档
<代码>
<书籍>
<书>
<标题>
XML简介
我知道 XQuery 听起来像是这里的解决方案,但我使用的是 Javascript,并且据我所知,Javascript 中的 XQuery 没有内置实现。
我想连同我需要的东西一起回报祖先。但如果我得到几个结果,它也应该可以工作。使用 XPath 可以吗?
I am using Javascript, and I want to return an XML document with the results I want.
For example, the XML document can be
<books>
<book>
<title>
Introduction to XML
</title>
</book>
<book>
<title>
Introduction to Javascript
</title>
</book>
</books>
and using this XPath expression:
//book[./title="Introduction to XML"]
I want to get a document like that
<books>
<book>
<title>
Introduction to XML
</title>
</book>
</books>
I know XQuery sounds like the solution here, but I am using Javascript, and there are no built-in implementations, as far as I know, for XQuery in Javascript.
I want to return the ancestors along with the thing I need. But it should also work if I get several results.. is this doable using XPath?
发布评论
评论(3)
XPath 无法更改源 XML 文档,也无法生成新的 XML 文档。
因此,必须为此使用一些其他技术。 XSLT 是一种专门为wxpressing 此类转换而设计的语言。
在大多数浏览器中,您可以使用由关联
PI(处理指令)。
大多数浏览器还提供某种在 Javascript 中启动 XSLT 转换的方法 - 请阅读浏览器文档。
XSLT 转换本身非常简单:
当将此转换应用于提供的 XML 文档时:
生成所需的正确结果:
XPath cannot change the source XML document and cannot produce a new XML document.
Therefore, some other technology has to be used for this. XSLT is a language especially designed for wxpressing such transformations.
In most browsers you can process an XML document with an XSLT stylesheet identified by an associating
<?xml-stylesheet ?>
PI (processong instruction).Most browsers also offer some way of initiating an XSLT transformation in Javascript -- read your browser documentation.
The XSLT transformation itself is very simple:
when this transformation is applied to the provided XML document:
the wanted, correct result is produced:
浏览器 JavaScript 环境附带默认的 Xml 文档对象模型解析器。
您可以利用该控件并将其解析为 Dom 解析样式。
Browser JavaScript Environment comes with default Xml Document Object Model Parser.
You can take advantage of that control and parse it as Dom Parsing Style.
一般来说,不,您不能仅使用 XPath 来做到这一点 - 它只是一种表达式语言。 XPath 无法创建节点,它只能选择它们。您可以(如您所选择的)选择一组节点,但不能将它们包装在其他节点中。
您当然可以改变@kadalmittai的建议并使用DOM API来选择您的节点,创建一个新文档并将您选择的节点克隆到其中,但鉴于您的要求相当简单,这是相当重量级的。
XSLT 在这里可能是更好的方法,但我对浏览器技术了解不够,无法告诉您如何在浏览器中使用它。
In general, no you can't do that with XPath on its own - it's only an expression language. XPath cannot create nodes it can only select them. You can (as you have) select a set of nodes but you can't then wrap them up in other nodes.
You certainly could vary @kadalmittai's suggestion and use the DOM API to select your nodes, create a new document and clone your selected nodes into it but that is fairly heavyweight given your fairly simple requirement.
XSLT might be a better approach here but I don't know enough about browser technologies to tell you how to use it in the browser.