简体   繁体   中英

How to parse xml with < using XmlStreamReader

I am trying to parse xml files. But there is an issue with <.

My XML file example:

<title>
<subtitle> The conclusion is p &lt; 0.1 </subtitle>
</title>

My code is:

XMLInputFactory factory = XMLInputFactory.newFactory();

XMLStreamReader reader = factory.createXMLStreamReader(StringSource);
while (reader.hasNext()) {
switch (reader.next()) {
 case XMLStreamReader.START_ELEMENT: {
  String tagName = reader.getLocalName();
  String path = parent.getPath() + "/" + tagName;
  
   parent.addChild(child);
  }
case XMLStreamReader.CHARACTERS: {
String text = reader.getText();

After parsing it, the text I got is: "0.1".

The output I expected is "The conclusion is p < 0.1"

I think the problem is at getText(), how can I fix that?

If you think the problem is getText(), Then rewrite as reader.toString() instead of getText();

Here you can see a parse code.

tring resumen = "";
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));
xmlEventReader.nextEvent();

while (xmlEventReader.hasNext()) {
     XMLEvent xmlEvent = xmlEventReader.nextEvent();

     if (xmlEvent.isStartElement()) {
         StartElement startElement = xmlEvent.asStartElement();

        if (startElement.getName().getLocalPart().equals("subtitle")) {
           xmlEvent = xmlEventReader.nextEvent();
           resumen = xmlEvent.toString();                            
        }
     }

}

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