简体   繁体   中英

How to read and write XML File without certain nodes in Java

I am trying to read an XML File and write a new XML file without the first node(root element) and the second node. Here an example..

I got this: afile.xml

<soap:Envelope>
 <soap:Body>
  <note>
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
  </note>
  </soap:Body>
</soap:Envelope>

and want this : bfile.xml

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

One way is to use XSLT, for instance XSLT 2.0 can do it with a simple stylesheet

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

<xsl:template match="/">
  <xsl:copy-of select="//note" copy-namespaces="no"/>
</xsl:template>

</xsl:stylesheet>

You need to use an XSLT 2.0 processor like Saxon 9 to run the code given above.

If you don't know the name of the element you want to copy then using <xsl:copy-of select="/*/*/*" copy-namespaces="no"/> instead of <xsl:copy-of select="//note" copy-namespaces="no"/> should do.

Try the following ...

import java.util.Map;

import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;

public class NoteExtract
{
public static void main(String[] args)
{
    try
    {
        String xml = "<soap:Envelope><soap:Body><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note></soap:Body></soap:Envelope>";

        Map<String, Object> map = new ToMap().convertToMap(xml);

        Map<String, Object> mapEnvelope = (Map<String, Object>) map.get("soap:Envelope");

        Map<String, Object> mapBody = (Map<String, Object>) mapEnvelope.get("soap:Body");

        String extractedXML = (new ToXML().convertToXML(mapBody, true)).toString();

        System.out.println("Extracted XML: " + extractedXML);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

 -------- XML Detected -------- 
 -------- Map created Successfully -------- 
 -------- Map Detected -------- 
 -------- XML created Successfully -------- 
Extracted XML: <note><to>Tove</to><body>Don't forget me this weekend!</body><from>Jani</from><heading>Reminder</heading></note>

Get the Conversion Box JAR for this ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM