使用jQuery根据XML的<y>标签值查找指定<field>的<value>值
<y> in XML Got it, so you need to pull the <value> of the <field> where <name> is "work", but only from the <x> node that has a specific <y> value. Let's break down two easy-to-implement solutions:
1. Use XPath (Quickest for One-Off Queries)
XPath is perfect for targeted XML searches. For your structure, here's the expression you'll need:
If you're looking for the <x> node where <y> is 12, use this:
//x[y="12"]/metadata/field[name="work"]/value/text()
Let's break that down:
//x[y="12"]: Grabs all<x>nodes where the child<y>has the text "12"/metadata/field[name="work"]: Drills into the<metadata>of that<x>node, then picks the<field>where<name>is "work"/value/text(): Pulls the actual text content from the<value>tag of that field
If you're using a command-line tool like xmllint, run this to get the result directly:
xmllint --xpath '//x[y="12"]/metadata/field[name="work"]/value/text()' your_xml_file.xml
For your sample XML, this would spit out true.
2. Python Code (For Programmatic Use)
If you need to do this in a script, Python's built-in xml.etree.ElementTree module works great. Here's a complete example:
import xml.etree.ElementTree as ET # Parse your XML file (use ET.fromstring() if working with an XML string instead) tree = ET.parse("your_file.xml") root = tree.getroot() # Set the target <y> value you want to match target_y = "12" # Loop through all <x> nodes to find the matching one for x_node in root.findall("x"): y_tag = x_node.find("y") if y_tag is not None and y_tag.text == target_y: # Now find the "work" field in this <x>'s metadata metadata = x_node.find("metadata") for field in metadata.findall("field"): name_tag = field.find("name") if name_tag is not None and name_tag.text == "work": value_tag = field.find("value") if value_tag is not None: print(f"Found the value: {value_tag.text}") break break
Run this, and it'll output Found the value: true for your sample. Just change target_y to "14" to match the other <x> node once your XML is complete.
Quick Notes
- Make sure your XML is well-formed: Your sample cuts off the second
<x>node—double-check all tags are closed and there's a root element wrapping everything. - Case sensitivity: XML (and XPath) are case-sensitive, so make sure "work", "y", etc., match exactly what's in your file.
内容的提问来源于stack exchange,提问作者Ancy

