LoginSignup
3
3

More than 5 years have passed since last update.

XSLTでXMLの属性を変更・削除・追加する

Last updated at Posted at 2018-01-23

XSL

test.xsl
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:x="http://www.w3.org/1999/xhtml">

  <xsl:output method="xml" encoding="utf-8" />

  <!-- 要素・属性をコピー -->
  <xsl:template match="/|node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <!-- 属性値を変更 -->
  <xsl:template match="x:div[@id='a_modify']/x:p/@style">
    <xsl:attribute name="style">color:blue;</xsl:attribute>
  </xsl:template>

  <!-- 属性を削除 -->
  <xsl:template match="x:div[@id='a_delete']/x:p/@style">
  </xsl:template>

  <!-- 属性を追加 -->
  <xsl:template match="x:div[@id='a_add']/x:p">
    <xsl:copy>
      <xsl:attribute name="style">color:red;</xsl:attribute>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

XML(in)

test_in.xml
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<html xml:lang="jp" lang="jp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>XSLTメモ (002)</title>
</head>
<body>
<div id="a_modify">
<h1>XSLTでXMLの属性の値を変更する</h1>
<p style="color:red;">style属性のcolorプロパティを変更する</p>
</div>
<div id="a_delete">
<h1>XSLTでXMLの属性を削除する</h1>
<p style="color:red;">style属性を削除する</p>
</div>
<div id="a_add">
<h1>XSLTでXMLの属性を追加する</h1>
<p>style属性を追加する</p>
</div>
</body>
</html>

XML(out)

test_out.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<html xml:lang="jp" lang="jp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>XSLTメモ (002)</title>
</head>
<body>
<div id="a_modify">
<h1>XSLTでXMLの属性の値を変更する</h1>
<p style="color:blue;">style属性のcolorプロパティを変更する</p>
</div>
<div id="a_delete">
<h1>XSLTでXMLの属性を削除する</h1>
<p>style属性を削除する</p>
</div>
<div id="a_add">
<h1>XSLTでXMLの属性を追加する</h1>
<p style="color:red;">style属性を追加する</p>
</div>
</body>
</html>
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3