1

Is there a way to read xml comments while parsing it using XStream with Java.

<!--
 Mesh:  three-dimensional box 100m x 50m x 50m Created By Sumit Purohit on 
 for a stackoverflow query.
-->  
<ParameterList name="Mesh">  
 <Parameter name="Domain Low Corner" type="Array double" value="{0.0, 0.0,  0.0}" /> 
 <Parameter name="Domain High Corner" type="Array double" value="{100.0, 50.0,50.0}" /> 
</ParameterList>

I currently use XStream to serialize/ de-serialize kind of xml above. I need to save comments as annotations on my POJO so that i can show it in UI.

I could not find anything in XStream for that.

DOM has DocumentBuilderFactory.setIgnoringComments(boolean) that let you include comments in the DOM tree and you can distinguish between type of Nodes.

Similarly C# has XmlReaderSettings.IgnoreComments

Community
  • 1
  • 1
Sumit Purohit
  • 168
  • 2
  • 12

2 Answers2

1

Try using LexicalHandler APIs to parse CData and Comments from an XML.

Arham
  • 2,072
  • 2
  • 18
  • 30
1

XStream can not process XML comments to my knowledge.

Here is another approach, which uses the LexicalHandler API:

import org.xml.sax.*;
import org.xml.sax.ext.*;
import org.xml.sax.helpers.*;

import java.io.IOException;

public class ReadXMLFile implements LexicalHandler {

  public void startDTD(String name, String publicId, String systemId)
      throws SAXException {
  }

  public void endDTD() throws SAXException {
  }

  public void startEntity(String name) throws SAXException {
  }

  public void endEntity(String name) throws SAXException {
  }

  public void startCDATA() throws SAXException {
  }

  public void endCDATA() throws SAXException {
  }

  public void comment(char[] text, int start, int length)
      throws SAXException {

    System.out.println("Comment: " + new String(text, start, length));
  }

  public static void main(String[] args) {
    // set up the parser
    XMLReader parser;
    try {
      parser = XMLReaderFactory.createXMLReader();
    } catch (SAXException ex1) {
      try {
        parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
      } catch (SAXException ex2) {
        return;
      }
    }

    try {
      parser.setProperty("http://xml.org/sax/properties/lexical-handler",new ReadXMLFile()
      );
    } catch (SAXNotRecognizedException e) {
      System.out.println(e.getMessage());
      return;
    } catch (SAXNotSupportedException e) {
      System.out.println(e.getMessage());
      return;
    }

    try {
      parser.parse("xmlfile.xml"); // <----  Path to XML file
    } catch (SAXParseException e) { // well-formedness error
      System.out.println(e.getMessage());
    } catch (SAXException e) { 
      System.out.println(e.getMessage());
    } catch (IOException e) {
    }
  }
}
Werner Kvalem VesterĂ¥s
  • 10,226
  • 5
  • 43
  • 50