2010-06-28 7 views
2

다음 구문을 얻을 수없는 XML 조각입니다 :선택 요소는 꽤 괜찮

$ cat short.xml 
<hostnames> 
    <hostname name="yahoo.com" type="user"/> 
    <hostname name="ir1.fp.vip.sp2.yahoo.com" type="PTR"/> 
</hostnames> 
<hostnames> 
    <hostname name="Inc.com" type="user"/> 
    <hostname name="www.inc.com" type="PTR"/> 
</hostnames> 

원하는 출력은 다음과 같습니다

yahoo.com | ir1.fp.vip.sp2.yahoo.com 
Inc.com | www.inc.com 

내가 지금까지 그 무엇을 가지고는 $ xml sel -t -m "// hostname"-v "@name"-n short.xml

Type = 조건을 올바르게 트랩 할 수없는 것 같습니다. TIA.

답변

3

당신은 xmlstarlet el 또는 뭔가 호스트 이름을 계산 한 후 같은 뭔가를 반복해야합니다 XML이 더 나은 디자인 된 경우

xmlstarlet sel -t -c "//hostnames[1]" short.xml | xmlstarlet sel -t -m "//hostname/@name" -v . -o ' | ' 

훨씬 쉽게 될 것입니다. : 한 번만 xmlstarlet을 사용

+0

도움이되었습니다. 감사. – galaxywatcher

4

두 개 솔루션 (필요 반복 없습니다) :

xmlstr=' 
<root> 
    <hostnames> 
    <hostname name="yahoo.com" type="user"/> 
    <hostname name="ir1.fp.vip.sp2.yahoo.com" type="PTR"/> 
    </hostnames> 
    <hostnames> 
    <hostname name="Inc.com" type="user"/> 
    <hostname name="www.inc.com" type="PTR"/> 
    </hostnames> 
</root> 
' 

echo "$xmlstr" | xmlstarlet sel -T -t -m "//hostnames" -m "hostname[@type='user']" -v '@name' -o " | " -b -m "hostname[@type='PTR']" -v '@name' -n 

echo "$xmlstr" | xmlstarlet sel -T -t -m "//hostname" -i "@type='user'" -v '@name' -o " | " -b -i "@type='PTR'" -v '@name' -n 
0

질문에 주어진 예제는 잘못된 XML이다.

xmlstarlet --version 
1.3.1 
compiled against libxml2 2.8.0, linked with 20800 
compiled against libxslt 1.1.26, linked with 10126 
xmlstarlet val -e short.xml 
short.xml:5.1: Extra content at the end of the document 
<hostnames> 
^ 
short.xml - invalid 

MITM으로 answer의 아이디어는 아주 좋은 치료입니다.