问题
I have this XML file
<?xml version="1.0" encoding="utf-8"?>
<xObject version="3.0" xmlns="http://schemas.microsoft.com/random/2006/objects">
<section id="*" type="product">
<table name="XFile">
<row sourceLineNumber="D:\bla\bla\">
<field>Borderish.fo</field>
<field>Documents</field>
<field>1</field>
<field>This line here 1</field>
</row>
<row sourceLineNumber="D:\blah\blah\">
<field>Charterish</field>
<field>Documents</field>
<field>1</field>
<field>This line here 2</field>
</row>
</table>
</section>
</xObject>
What I want to do is select every 4th element with xmlstarlet.
I managed to do this using XmlPad like this: //table[@name='XFile']/row/field[4]/text(), but unfortunately I must do this using xmlstarlet.
Also, if I delete the xObject's attributes/namespace, seems to work using the command: xml sel -t -v "//table/row/field[4]/text()" test.xml
Does anyone has any idea how this can be done? It's my first time trying to evaluate xpath.
Regards, Stefan
回答1:
You have to define a namespace and use it in your XPath expression:
$ xmlstarlet sel -N ns="http://schemas.microsoft.com/random/2006/objects" -t -v "//ns:table/ns:row/ns:field[4]/text()" test.xml
The command above uses -N ns="http://schemas.microsoft.com/random/2006/objects"
to declare a namespace named ns
that is set to the value of the default namespace in your XML file. Then the XPath expression is set so that this ns
prefix is used.
来源:https://stackoverflow.com/questions/21729396/xmlstarlet-selecting-element-by-its-position-number