Updating xml elements using ant

ⅰ亾dé卋堺 提交于 2019-12-25 03:16:24

问题


I have an XSL file, which acts as a configuration file for my application. In fact it is an XML file, which has the elements wrapped around it. This file is called Config.xsl:

<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"           xmlns="http://www.example.org/Config">
 <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"               standalone="yes" />
 <xsl:template match="/">
 <Config>
      <Test>somevalue</Test>
      <Test1>someothervalue</Test1>
 </Config>
 </xsl:template>

I would like the change the value of element Test1 with a newvalue.

Below is my ant code, which I am using to update the values.

<?xml version="1.0" encoding="UTF-8" ?>
<project name="Scripts" default="test">
<taskdef resource="net/sf/antcontrib/antcontrib.properties" />
<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"/>
<target name="test">
    <xmltask source="Config.xsl" dest="Config.xsl">
        <replace path="Config/Test1/text()" withText="newvalue" />
    </xmltask>
</target>
</project>

I would appreciate if anyone can let me know how to get this work.


回答1:


It seems you are confused with namespace. You must handle it before replacing anything. For more details how XML Task handle it goto https://today.java.net/pub/a/today/2006/11/01/xml-manipulation-using-xmltask.html#paths-and-namespaces. However, you may used this code to get our desired output:

input:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.example.org/Config">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" standalone="yes"/>
  <xsl:template match="/">
    <Config>
      <Test>somevalue</Test>
      <Test1>someothervalue</Test1>
    </Config>
  </xsl:template>
</xsl:stylesheet>

ANT script:

<project name="XML-VALIDATION" default="main" basedir=".">
  <taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"/>
  <target name="main">
    <xmltask source="config.xsl" dest="output.xml">
      <replace path="//:Config/:Test1/text()">xxxxxxx</replace>
    </xmltask>
  </target>
</project>

output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.example.org/Config" version="1.0">
  <xsl:output encoding="UTF-8" indent="yes" method="xml" standalone="yes" version="1.0"/>
  <xsl:template match="/">
    <Config>
      <Test>somevalue</Test>
      <Test1>xxxxxxx</Test1>
    </Config>
  </xsl:template>
</xsl:stylesheet>


来源:https://stackoverflow.com/questions/19694880/updating-xml-elements-using-ant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!