0

Here is what I have. It clearly doesn't do what it supposed to and it even crashed. Is something wrong or is there any other tool that can help me parse XML in BASH?

:~$ cat test.xml 
<project xmlns="http://www.netbeans.org/ns/project/1">
  <type>org.netbeans.modules.ant.freeform</type>
</project>

:~$ xmllint --xpath '//type/text()' test.xml 
Segmentation fault (core dumped)

:~$ xmllint --xpath '//type' test.xml 
XPath set is empty
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
user219882
  • 15,274
  • 23
  • 93
  • 138

2 Answers2

0

To search for a namespaced element, you can test the local name, like this:

xmllint --xpath '//*[local-name()="type"]/text()' test.xml

A more precise way would be

xmllint --xpath '//*[namespace-uri()="http://www.netbeans.org/ns/project/1" and local-name()="type"]/text()' test.xml
Ken Geis
  • 904
  • 6
  • 17
-1

Your problem is that your XML... Is not a valid XML file.

Try this before :

sed -i '1i <?xml version="1.0" encoding="UTF-8"?>' test.xml

And after testing, you have a namespace problem so try this :

xmllint --shell test.xml
/ > setns x=http://www.netbeans.org/ns/project/1
/ > xpath /x://type/text()
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I had that in there and it didn't work either so I removed it just to check that xmllint does not have a problem with that... And it's still a valid XML file, even without it (other tools don't mind if the first line is missing) – user219882 Mar 13 '13 at 16:23
  • 1
    The problem is your namespace, not the XML first line – Gilles Quénot Mar 13 '13 at 16:25
  • how can this be a problem? as I see it, I would blame the tool, not the XML structure – user219882 Mar 13 '13 at 16:27
  • it works without the namespace but I just can't remove it randomly :) – user219882 Mar 13 '13 at 16:29
  • `xpath /x://type/text()` gives me `XPath error : Invalid expression` pointing at the `:/` part – user219882 Mar 13 '13 at 16:34
  • also in the real world I have many different namespaces in the document so it would be great if I could just make the tool work without specifiyng them... – user219882 Mar 13 '13 at 16:35
  • Have you tried without `:` ? – Gilles Quénot Mar 13 '13 at 16:58
  • yes, no change... but i want those namespaces to remain there and without need to specify them explicitely... also --shell option does not work for me since I have to use xmllint in a script – user219882 Mar 14 '13 at 10:07