명령줄에서 XML을 예쁘게 인쇄하는 방법은 무엇입니까?
관련:JSON을 (unix) 셸 스크립트로 프리프린팅하려면 어떻게 해야 합니까?
XML을 사람이 읽을 수 있는 형태로 포맷하는 (unix) 셸 스크립트가 있습니까?
기본적으로 다음과 같은 변화를 주었으면 합니다.
<root><foo a="b">lorem</foo><bar value="ipsum" /></root>
... 다음과 같은 형태로.
<root>
<foo a="b">lorem</foo>
<bar value="ipsum" />
</root>
xmllint
이 유틸리티는 다음과 함께 제공됩니다.
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xmllint --format -
XML::Twig
이 명령은 XML::Twigperl module과 함께 제공됩니다. 때때로xml-twig-tools
패키지:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xml_pp
xmlstarlet
이 명령은 다음과 함께 제공됩니다.
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xmlstarlet format --indent-tab
tidy
패키지를 확인합니다.
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
tidy -xml -i -
파이썬
Python은 XML을 포맷할 수 있습니다(레거시 python2에서도 작동).
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
python -c 'import sys; import xml.dom.minidom; s=sys.stdin.read(); print(xml.dom.minidom.parseString(s).toprettyxml())'
saxon-lint
필요한 항목:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
saxon-lint --indent --xpath '/' -
saxon-HE
필요한 항목:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \
-s:- -qs:/ '!indent=yes'
xidel
필요한 항목:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xidel -s - -se . --output-node-format=xml --output-node-indent
(Reino에게 크레딧 제공)
모든 명령에 대한 출력:
<root>
<foo a="b">lorem</foo>
<bar value="ipsum"/>
</root>
xmllint --format yourxmlfile.xml
xmllint는 명령줄 XML 도구이며 다음에 포함됩니다.libxml2
(http://xmlsoft.org/) .
================================================
가 : libxml2
를 할 수 installed 를 사용하여 설치할 수 있습니다.
센트OS
cd /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd
우분투
sudo apt-get install libxml2-utils
시그윈
apt-cyg install libxml2
맥OS
하여 MacOS에 작업을 수행하십시오. 로 MacOS 하려면 하면 만 하면 만 로 하려면 brew install libxml2
깃
에서도 사용 : 를 Git 에서도 :git clone git://git.gnome.org/libxml2
먼저 설치해야 할 수도 있는 정리정돈을 사용할 수도 있습니다(예: Ubuntu: sudo).apt-get install tidy
).
이를 위해서는 다음과 같은 것을 발행해야 합니다.
tidy -xml -i your-file.xml > output.xml
참고: 가독성 플래그가 추가로 많이 있지만 단어를 바꾸는 행동은 (http://tidy.sourceforge.net/docs/quickref.html) 을 푸는 데 약간 짜증이 납니다.
macOS/대부분의 유닉스에 아무것도 설치하지 않음.
사용하다tidy
cat filename.xml | tidy -xml -iq
파일 보기를 cat으로 리디렉션하여 xml의 파일 형식을 지정하고 조용한 출력으로 들여쓰기하면 오류 출력이 억제됩니다.JSON도 함께 작업합니다.-json
.
파일을 언급하지 않으셨기 때문에 명령줄에서 XML 문자열을 표준 입력으로 제공하고자 합니다.이 경우 다음을 수행합니다.
$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | xmllint --format -
for f in *.xml; do xmllint -o $f --format $f; done
Daniel Veillard가 다음과 같습니다.
생각합니다
xmllint -o tst.xml --format tst.xml
파서가 출력을 열어 직렬화하기 전에 입력을 트리에 완전히 로드하므로 안전해야 합니다.
들여쓰기 수준은 다음에 의해 제어됩니다.XMLLINT_INDENT
환경 변수는 기본적으로 2칸입니다.들여쓰기를 4개의 공백으로 변경하는 방법 예:
XMLLINT_INDENT=' ' xmllint -o out.xml --format in.xml
부족할 수도 있습니다.--recover
XML 문서가 깨졌을 때의 옵션입니다.또는 엄격한 XML 출력으로 약한 HTML 파서를 시도해 보십시오.
xmllint --html --xmlout <in.xml >out.xml
--nsclean
,--nonet
,--nocdata
,--noblanks
등이 유용할 수 있습니다.맨 페이지를 읽습니다.
apt-get install libxml2-utils
dnf install libxml2
apt-cyg install libxml2
brew install libxml2
이 간단한 해결책은 움푹 들어간 부분을 제공하지 않지만, 그럼에도 불구하고 사람의 눈에는 훨씬 더 쉽습니다.또한 grep, head, awk 등 간단한 도구로 xml을 보다 쉽게 처리할 수 있습니다.
사용하다sed
'<'을 새 줄로 앞에 놓는 것으로 바꿉니다.
그리고 질스가 언급한 것처럼, 이것을 생산에 사용하는 것은 아마도 좋지 않을 것입니다.
# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l
# check the output looks generally ok
sed 's/</\n</g' sample.xml | head
# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml
이것은 내 맥에서 작동하는 것을 찾는 데에 영원히 걸렸습니다.제게 도움이 된 것은 다음과 같습니다.
brew install xmlformat
cat unformatted.html | xmlformat
yq는 XML을 예쁜 인쇄하는 데 사용할 수 있습니다. 들여쓰기를 정의하는 옵션이 있습니다.
yq --input-format xml --output-format xml --indent 2
xidel 포함:
$ xidel -s input.xml -e . --output-node-format=xml --output-node-indent
$ xidel -s input.xml -e 'serialize(.,{"indent":true()})'
$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | \
xidel -se . --output-node-format=xml --output-node-indent
$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | \
xidel -se 'serialize(.,{"indent":true()})'
편집:
면책 사항: 일반적으로 다음과 같은 성숙한 도구를 설치하는 것을 선호해야 합니다.xmllint
이런 일을 하는 거죠 XML/HTML은 아주 엉망진창일 수도 있어요그러나 새로운 툴을 수동으로 설치하는 것보다 기존 툴링을 사용하는 것이 더 바람직하며 XML의 소스가 충분히 유효할 것이라고 확신하는 경우도 있습니다.그 중 하나를 위해 이 대본을 썼지만, 드물기 때문에 주의해야 합니다.
손으로만 하는 것이 '그렇게' 어렵지 않고, 작업을 수행하기 위해 추가 도구를 설치하고 싶지 않을 때도 있기 때문에 순수한 Bash 솔루션을 추가하고 싶습니다.
#!/bin/bash
declare -i currentIndent=0
declare -i nextIncrement=0
while read -r line ; do
currentIndent+=$nextIncrement
nextIncrement=0
if [[ "$line" == "</"* ]]; then # line contains a closer, just decrease the indent
currentIndent+=-1
else
dirtyStartTag="${line%%>*}"
dirtyTagName="${dirtyStartTag%% *}"
tagName="${dirtyTagName//</}"
# increase indent unless line contains closing tag or closes itself
if [[ ! "$line" =~ "</$tagName>" && ! "$line" == *"/>" ]]; then
nextIncrement+=1
fi
fi
# print with indent
printf "%*s%s" $(( $currentIndent * 2 )) # print spaces for the indent count
echo $line
done <<< "$(cat - | sed 's/></>\n</g')" # separate >< with a newline
스크립트 파일에 붙여넣고 xml에 pipe를 넣습니다.이것은 xml이 모두 한 줄에 있고 어느 곳에도 추가 공간이 없다고 가정합니다.한 명은 쉽게 추가할 수 있었습니다.\s*
그것을 고치기 위해 정규군에게.
다음과 같습니다.
nicholas@mordor:~/flwor$
nicholas@mordor:~/flwor$ cat ugly.xml
<root><foo a="b">lorem</foo><bar value="ipsum" /></root>
nicholas@mordor:~/flwor$
nicholas@mordor:~/flwor$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> create database pretty
Database 'pretty' created in 231.32 ms.
>
> open pretty
Database 'pretty' was opened in 0.05 ms.
>
> set parser xml
PARSER: xml
>
> add ugly.xml
Resource(s) added in 161.88 ms.
>
> xquery .
<root>
<foo a="b">lorem</foo>
<bar value="ipsum"/>
</root>
Query executed in 179.04 ms.
>
> exit
Have fun.
nicholas@mordor:~/flwor$
파일이 아닌 데이터베이스에 있다는 이유만으로 가능합니다.내 마음엔 작업하기가 더 쉽죠.
다른 사람들이 이미 이 문제를 해결했다는 믿음에 동의하는 것입니다.당신이 원한다면, 의심할 여지없이.eXist
포맷이 더 나을 수도 있습니다.xml
, 아니면 아주 좋습니다.
물론 다양한 방법으로 데이터를 쿼리할 수도 있습니다.최대한 간단하게 했습니다.GUI를 사용할 수도 있지만 콘솔을 지정했습니다.
언급URL : https://stackoverflow.com/questions/16090869/how-to-pretty-print-xml-from-the-command-line
'programing' 카테고리의 다른 글
'appcmd'라는 용어가 cmdlet의 이름으로 인식되지 않습니다. (0) | 2023.09.19 |
---|---|
잘못된 작업예외: 컨텍스트의 모델에 이 유형이 포함되어 있지 않기 때문에 '역할'에 대한 DbSet을 만들 수 없습니다. (0) | 2023.09.19 |
C# Double - ToString() 형식으로 소수점 두 자리를 사용하지만 반올림하지 않음 (0) | 2023.09.14 |
CSS/자바스크립트:여러 상태로 회전 원형 메뉴를 만드는 방법은? (0) | 2023.09.14 |
키 누르기 이벤트 후 jQuery.val() AFTER 이벤트를 받으려면 어떻게 해야 합니까? (0) | 2023.09.14 |