4 ms·
I guess the correct answer depends upon the requirement. I like this way <root> <item key="name">John</item> <item key="city">London</item> </root>
by robofanatic 7y ago
I guess the correct answer depends upon the requirement.
I like this way
<root>
<item key="name">John</item>
<item key="city">London</item>
</root>
So I can use this xpath to get the person's name:
//root/item[@key="name"]/text()
Not sure what would be the xpath to get the name if the XML was
<root>
<item>
<key>Name</key>
<value>John</value>
</item>
<item>
<key>City</key>
<value>London</value>
</item>
</root>
This is a better example:
<employees>
<employee id="1">
<field name="name">John</field>
<field name="city">London</field>
</employee>
<employee id="2">
<field name="name">Jack</field>
<field name="city">Boston</field>
</employee>
<employees>
- scandox 7y agoIf you accept the author's premise then all of these (including his) are wrong uses of XML.
- elFarto 7y agoThe XPath for the second one would be: //root/item/key[text()="Name"]/../value/text()
- icebraining 7y agoAlternatively //root/item[key[text()="Name"]]/value/text()
- benibela 7y agoYou usually do not need to use text() in xpath, so this should work the same: //root/item[key="name"]/value
- commandlinefan 7y agoWell, actually, an even better example is: <employees> <employee id="1"> <name>John</name> <city>London</city> </employee> <employee id="1"> <name>Jack</name> <city>Boston</city> </employee> I know what you’re trying to do there - you’re trying to “future-proof” your schema by allowing introduction of arbitrary new elements. Which means that there’s no standard way to guard against somebody omitting a required field (like “name”) or adding a new field like “creditCardNumber” - other than to document your acceptable key values in a non-standard format and add defensive code that a validating parser would have given you. You’re better off taking as much advantage of the format as you can.
- deleted 7y ago[deleted]