读取和替换xsl-fo文件中的标记

时间:2011-01-20 16:33:29

标签: java xml xsl-fo

我需要阅读,找到标签并将其替换为java中的.fo文件。请帮我看看怎么样?我已经阅读了一些主题,但我是java的新手,并且遇到了一些问题......对于这个文件,我必须找到<fo:external-graphic src="url('Images/box.jpg')"/>标签,并在其中替换url =“(另一条路径)”!

 <fo:block font-weight="bold" space-before.optimum="12pt" space-after.optimum="12pt" padding="0.1in" border="thin solid black">
      The manufacturer declines every liability with regard to any direct or 
      consequential damage caused by the equipment to you, your body parts, 
      your personal belongings, your domestic animals e/o beloved relatives. 
      Use this equipment at your own risk, and let God protect your fingers! 
    </fo:block>

    <fo:block space-before.optimum="6pt">Have fun with our stuff!</fo:block>

  </fo:block><fo:block id="d0e81" text-align="justify" font="11pt Times" line-height="1.3" space-before.minimum="18pt" space-before.conditionality="retain">
    <fo:block font="bold 14pt Helvetica" keep-together.within-column="always" keep-with-next.within-column="always" space-before.minimum="6pt" space-before.optimum="12pt" space-before.conditionality="retain" space-after.optimum="3pt" background-color="silver" padding="3pt" border-top="thin solid black" border-bottom="thin solid black">B.  Unpacking &amp; Installing </fo:block>
    <fo:block space-before.optimum="6pt"> 
      The universal hammer comes shipped in a <fo:wrapper font-style="italic" color="blue" rx:key="carton box">carton box</fo:wrapper> 

  (see Fig. 1)
.
    </fo:block><fo:block margin="3pt" border="thin ridge silver" padding="3pt" space-before.optimum="6pt" space-after.optimum="6pt" text-align="center" font-style="italic" font-family="Helvetica" keep-together.within-column="always"><fo:block text-align="center">
    <fo:external-graphic src="url('Images/box.jpg')"/>
    </fo:block>
      Fig. 1.
      Shipping Box.</fo:block> 

1 个答案:

答案 0 :(得分:0)

创建一个DOM,然后获取名为fo:external-graphic的所有元素。然后,您可以将src属性更改为您喜欢的任何内容。以下是一些示例代码,可帮助您入门:

//parse the xml file
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("file.xml"));

//get all elements called fo:external-graphic
NodeList list = doc.getElementsByTagName("fo:external-graphic");
for(int i = 0 ; i < list.getLength() ; i++){
    Element element = (Element)list.item(i);
    NamedNodeMap attributes = element.getAttributes();

    //change the src attribute
    Attr src = (Attr)attributes.getNamedItem("src");
    System.out.println(src.getValue());
    src.setValue("url('another/path/box.jpg')");
}

//let's print out the resulting doc for debugging purposes
OutputFormat format = new OutputFormat(doc);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(doc);
System.out.println(out.toString());