쉘 스크립트/명령을 사용하여 xml 파일 편집

쉘 스크립트/명령을 사용하여 xml 파일 편집

unix 스크립트나 명령을 사용하여 이 작업을 수행해야 합니다. /home/user/app/xmlfiles에 다음과 같은 xml 파일이 있습니다.

<book>
   <fiction type='a'>
      <author type=''></author>
   </fiction>
   <fiction type='b'>
      <author type=''></author>
   </fiction>
   <Romance>
       <author type=''></author>
   </Romance>
</book>

소설의 작가 유형을 로컬로 편집하고 싶습니다.

   <fiction>
      <author type='Local'></author>
   </fiction>

작성자 유형을 변경해야 합니다.속성이 b인 픽션 태그홀로. 유닉스 쉘 스크립트나 명령을 사용하여 이 문제를 해결하도록 도와주세요. 감사해요 !

답변1

<author type=''><\/author>으로 바꾸려면 <author type='Local'><\/author>다음 명령을 사용할 수 있습니다 sed.

sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file

하지만 XML을 다룰 때는 다음과 같은 XML 파서/편집기를 추천합니다.xmlstarlet:

$ xmlstarlet ed -u /book/*/author[@type]/@type -v "Local"  file
<?xml version="1.0"?>
<book>
  <fiction>
    <author type="Local"/>
  </fiction>
  <Romance>
    <author type="Local"/>
  </Romance>
</book>

-L변경 사항을 인쇄하는 대신 파일을 인라인으로 편집하려면 플래그를 사용하세요 .

답변2

xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml

답변3

xsl 문서를 사용 doThis.xsl하여 source.xmlwith xsltprocnewFile.xml.

xsl은 이에 대한 답변을 기반으로 합니다.질문.

doThis.xsl이것을 파일 에 넣어라

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no"/> 

<!-- Copy the entire document    -->

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!-- Copy a specific element     -->

<xsl:template match="/book/fiction[@type='b']/author">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>

<!--    Do something with selected element  -->
            <xsl:attribute name="type">Local</xsl:attribute>

        </xsl:copy>
</xsl:template>

</xsl:stylesheet> 

이제 우리는newFile.xml

$:   xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml 

이것은newFile.xml

<?xml version="1.0" encoding="UTF-8"?>
<book>
   <fiction type="a">
      <author type=""/>
   </fiction>
   <fiction type="b">
      <author type="Local"/>
   </fiction>
   <Romance>
       <author type=""/>
   </Romance>
</book>

b형 소설을 찾는 데 사용되는 표현은 입니다 XPath.

답변4

를 사용하면 매우 쉽습니다 sed. 다음 스크립트는 파일의 내용을 변경 하고 원본을 백업으로 a.xml저장합니다 .a.bak

그것이 하는 일은 각 파일에서 문자열을 검색 <author type=''>하고 이를 <author type='Local'>. 수정 /g자는 가능하면 각 줄에서 2개 이상의 대체를 시도한다는 것을 의미합니다(예제 파일에는 필요하지 않음).

sed -i.bak "s/<author type=''>/<author type='Local'>/g" a.xml

관련 정보