javascript 使用 jQuery 查找 XML 节点并使用其值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6554114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find an XML Node Using jQuery And Use Its Values
提问by Nathan Campos
I'm using a XML file like this:
我正在使用这样的 XML 文件:
<Test>
<Unit>
<Title>Test 1</Title>
<Date>01/07/2011</Date>
<Content format="html"><![CDATA[Here goes some content]]></Content>
</Unit>
<Unit>
<Title>Testing New XML</Title>
<Date>27/06/2011</Date>
<Content format="html"><![CDATA[Here goes some content]]></Content>
</Unit>
<!-- A lot of stuff like this -->
</Test>
I want to use jQuery to search on the XML document for a <Title>
given and get its entire <Unit>
, so I can work with the values like this:
我想使用 jQuery 来搜索<Title>
给定的 XML 文档并获取它的整个<Unit>
,所以我可以使用这样的值:
function append(title, date, content) {
$("#Unit").append("<h1 id='title'><b>" + title + "</b></h1><h2 id='date'>" + date + "</h2><p>" + content + "</p>");
}
How can I do this?
我怎样才能做到这一点?
PS: I've been using thisas the base of my XML reading
PS:我一直以此作为我阅读 XML 的基础
回答by RyanPitts
Is this what you're looking for? Click Here(jsFiddle link)
这是你要找的吗? 单击此处(jsFiddle 链接)
In that code you'll have to get the XML and store it in a variable first like i did. The code may not be exactly what you're looking for but it may be a good starting point. Play with the code and let me know if this is what you're looking for or not.
在该代码中,您必须像我一样首先获取 XML 并将其存储在变量中。该代码可能不是您正在寻找的确切代码,但它可能是一个很好的起点。玩代码,让我知道这是否是您正在寻找的。
You could also try this (same code as jsFiddle link but just using alerts instead of appending the data to the DOM)
你也可以试试这个(与 jsFiddle 链接相同的代码,但只是使用警报而不是将数据附加到 DOM)
var xml = "<Test><Unit><Title>Test 1</Title><Date>01/07/2011</Date><Content format='html'>some content here</Content></Unit><Unit><Title>Testing New XML</Title><Date>27/06/2011</Date><Content format='html'>some more content here</Content></Unit></Test>";
$(xml).find("Unit").each(function(){
if($(this).find("Title").length > 0){
var unitData = $(this).text();
alert(unitData);
}
});
That should give you two alerts.
这应该给你两个警报。
回答by bcoughlan
$("#Unit")
selects all elements with ID "unit".
$("#Unit")
选择 ID 为“unit”的所有元素。
To select all Unit element use $("Unit")
选择所有单位元素使用 $("Unit")
Edit: If you have a Title element in a variable, you can get the Unit using $(myTestVariable).closest("Unit")
编辑:如果变量中有 Title 元素,则可以使用 $(myTestVariable).closest("Unit")
回答by Lightness Races in Orbit
The selector #Unit
looks for nodes with an id
attribute equal to "Unit"
.
选择器#Unit
查找id
属性等于 的节点"Unit"
。
You need the selector Unit
, which looks for Unit
nodes.
您需要 selector Unit
,它会查找Unit
节点。