IT

XML 명령 줄 처리를위한 Grep 및 Sed

lottoking 2020. 6. 16. 07:58
반응형

XML 명령 줄 처리를위한 Grep 및 Sed


쉘 스크립팅을 수행 할 때 일반적으로 데이터는 csv와 같은 단일 행 레코드 파일에 있습니다. 이와이 데이터를 처리하기 위해 정말 간단 grep하고 sed. 그러나 XML을 자주 다루어야하므로 명령 줄을 통해 해당 XML 데이터에 대한 액세스를 스크립트로 작성하는 방법을 정말로 원합니다. 가장 좋은 도구는 무엇입니까?


xmlstarlet이 이런 종류의 것을 꽤 잘 발견했습니다.

http://xmlstar.sourceforge.net/

대부분의 배포 저장소에서도 사용 가능해야합니다. 입문 튜토리얼은 다음과 같습니다.

http://www.ibm.com/developerworks/library/x-starlet.html


유망한 도구 :

  • nokogiri : XPath 및 CSS 선택기를 사용하여 루비로 HTML / XML DOM 파싱

  • hpricot : 더 이상 사용되지 않음

  • fxgrep : 자체 XPath와 유사한 구문을 사용하여 문서를 쿼리합니다. SML로 작성되었으므로 설치가 어려울 수 있습니다.

  • LT XML : SGML의 포함 도구에서 파생 된 XML 툴킷 sggrep, sgsort, xmlnorm등이있다. 자체 쿼리 구문을 사용합니다. 문서는 매우 형식적입니다. LT XML 2는 XPath, XInclude 및 기타 W3C 표준을 지원한다고 주장합니다.

  • xmlgrep2 : XPath를 사용한 간단하고 강력한 검색 XML :: LibXML 및 libxml2를 사용하여 Perl로 작성되었습니다.

  • XQSharp : XPath의 확장 인 XQuery를 지원합니다. .NET Framework 용으로 작성되었습니다.

  • xml-coreutils : GNU coreutils와 동등한 Laird Breyer 툴킷. 이상적인 툴킷에 포함되어야 할 내용 에 대한 흥미로운 에세이 에서 논의했습니다 .

  • xmldiff : 두 개의 xml 파일을 비교하는 간단한 도구입니다.

  • xmltk : 데비안, 우분투, 페도라 또는 macports에 패키지가없는 것 같고 2007 년 이후 릴리스가 없었으며 이식 할 수없는 빌드 자동화를 사용합니다.

xml-coreutils는 가장 잘 문서화되고 가장 UNIX 지향적 인 것 같습니다.


Joseph Holsten의 훌륭한 목록에 Perl 라이브러리 XML :: XPath와 함께 제공되는 xpath 명령 줄 스크립트를 추가합니다. XML 파일에서 정보를 추출하는 좋은 방법 :

 xpath -q -e '/entry[@xml:lang="fr"]' *xml

또한이 xml22xml쌍. 일반적인 문자열 편집 도구로 XML을 처리 할 수 ​​있습니다.

예. q.xml :

<?xml version="1.0"?>
<foo>
    text
    more text
    <textnode>ddd</textnode><textnode a="bv">dsss</textnode>
    <![CDATA[ asfdasdsa <foo> sdfsdfdsf <bar> ]]>
</foo>

xml2 < q.xml

/foo=
/foo=   text
/foo=   more text
/foo=   
/foo/textnode=ddd
/foo/textnode
/foo/textnode/@a=bv
/foo/textnode=dsss
/foo=
/foo=    asfdasdsa <foo> sdfsdfdsf <bar> 
/foo=

xml2 < q.xml | grep textnode | sed 's!/foo!/bar/baz!' | 2xml

<bar><baz><textnode>ddd</textnode><textnode a="bv">dsss</textnode></baz></bar>

추신 html2/도 2html있습니다.


xmllint를 사용할 수 있습니다 :

xmllint --xpath //title books.xml

대부분의 배포판과 함께 번들로 제공되며 Cygwin과 함께 번들로 제공됩니다.

$ xmllint --version
xmllint: using libxml version 20900

보다:

$ xmllint
Usage : xmllint [options] XMLfiles ...
        Parse the XML files and output the result of the parsing
        --version : display the version of the XML library used
        --debug : dump a debug tree of the in-memory document
        ...
        --schematron schema : do validation against a schematron
        --sax1: use the old SAX1 interfaces for processing
        --sax: do not build a tree but work just at the SAX level
        --oldxml10: use XML-1.0 parsing rules before the 5th edition
        --xpath expr: evaluate the XPath expression, inply --noout

If you're looking for a solution on Windows, Powershell has built-in functionality for reading and writing XML.

test.xml:

<root>
  <one>I like applesauce</one>
  <two>You sure bet I do!</two>
</root>

Powershell script:

# load XML file into local variable and cast as XML type.
$doc = [xml](Get-Content ./test.xml)

$doc.root.one                                   #echoes "I like applesauce"
$doc.root.one = "Who doesn't like applesauce?"  #replace inner text of <one> node

# create new node...
$newNode = $doc.CreateElement("three")
$newNode.set_InnerText("And don't you forget it!")

# ...and position it in the hierarchy
$doc.root.AppendChild($newNode)

# write results to disk
$doc.save("./testNew.xml")

testNew.xml:

<root>
  <one>Who likes applesauce?</one>
  <two>You sure bet I do!</two>
  <three>And don't you forget it!</three>
</root>

Source: https://serverfault.com/questions/26976/update-xml-from-the-command-line-windows


There're also xmlsed & xmlgrep of the NetBSD xmltools!

http://blog.huoc.org/xmltools-not-dead.html


Depends on exactly what you want to do.

XSLT may be the way to go, but there is a learning curve. Try xsltproc and note that you can hand in parameters.


There's also saxon-lint from command line with the ability to use XPath 3.0/XQuery 3.0. (Other command-line tools use XPath 1.0).

EXAMPLES :

http/html:

$ saxon-lint --html --xpath 'count(//a)' http://stackoverflow.com/q/91791
328

xml :

$ saxon-lint --xpath '//a[@class="x"]' file.xml

XQuery might be a good solution. It is (relatively) easy to learn and is a W3C standard.

I would recommend XQSharp for a command line processor.


I first used xmlstarlet and still using it. When the query gets tough, i need XML's xpath2 and xquery feature support I turn to xidel http://www.videlibri.de/xidel.html


D. Bohdan maintains an open source GitHub repo that keeps a list of command line tools for structured text tools, there a section for XML/HTML tools:

https://github.com/dbohdan/structured-text-tools#xml-html


JEdit has a plugin called "XQuery" which provides querying functionality for XML documents.

Not quite the command line, but it works!

참고URL : https://stackoverflow.com/questions/91791/grep-and-sed-equivalent-for-xml-command-line-processing

반응형