XML 파일 계층 내에서 찾기-바꾸기

XML 파일 계층 내에서 찾기-바꾸기

디렉토리 전체에 약 350개의 XML 파일이 분산되어 있습니다 /abc. alt 속성의 값이 정확히 ''인 모든 인스턴스를 찾고 싶습니다.이러쿵 저러쿵':

<image alt="blah blah" src="../webcontent/filename.png">
    <caption>
        Figure 1.1: Typical Components of Blah Blah
    </caption>
</image>

속성 값을 (개행 제거) alt로 묶인 내용으로 바꿉니다 .caption

<image alt="Figure 1.1: Typical Components of Blah Blah" src="../webcontent/filename.png">
    <caption>
        Figure 1.1: Typical Components of Blah Blah
    </caption>
</image>

저는 Ubuntu나 Windows에서 스크립트를 실행하거나 텍스트 편집 도구를 사용하는 데 열려있습니다.

줄바꿈과 들여쓰기가 일관적이라고 가정하는 것은 안전하지 않습니다. 또한 모든 이미지에 캡션이 있는 것은 아닙니다. 경로의 모든 XML 문서는 올바른 형식입니다.

이 대체품을 내부에서 스크립팅하는 간단한 방법이 있습니까? 나는 단일 파일에 대해 작동하는 것을 열려고 합니다. 재귀적으로 실행되도록 확장할 수 있습니다.

답변1

단일 파일의 경우 다음 XSLT 스타일시트가 작업을 수행합니다.

<t:transform version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform">
  <t:template match="node()|@*">
    <t:copy>
      <t:apply-templates select="node()|@*"/>
    </t:copy>
  </t:template>
  <t:template match="image/@alt[. = 'blah blah']">
    <t:attribute name="alt" select="normalize-space(../caption)"/>
  </t:template>
</t:transform>

여러 파일을 처리하려면 일부 쉘 스크립트, Ant 스크립트 또는 이와 유사한 것(또는 xmlsh 참조)에서 스타일시트를 여러 번 호출할 수 있습니다. 또는 Saxon과 같은 XSLT 2.0 프로세서를 사용하는 경우 XSLT 자체 내에서 스크립팅할 수 있습니다. collection() 함수를 사용하여

답변2

다음을 사용할 수도 있습니다 xmlstarlet.

xmlstarlet ed -u '//image/@alt[.= "blah blah"]' -x "normalize-space(../caption/text())"

관련 정보