简体   繁体   中英

Convert the string content into an XMLStreamReader

您好我想知道我们如何转换XML标签形式的字符串内容,我需要将其转换为XMLStreamReader

You can use XMLInputFactory.createXMLStreamReader , passing in a StringReader to wrap your string.

String text = "<foo>This is some XML</foo>";
Reader reader = new StringReader(text);
XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory()
XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);

I assume you want to read XML content from a String via an XMLStreamReader . You can do that like this:

public XMLStreamReader readXMLFromString(final String xmlContent)
{
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final StringReader reader = new StringReader(xmlContent);
    return inputFactory.createXMLStreamReader(reader);
}
//Intialize XMLInputFactory
XMLInputFactory factory = XMLInputFactory.newInstance();

//Reading from xml file and creating XMLStreamReader
XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(
               file));
String currentElement = "";

//Reading all the data
while(reader.hasNext()) {
   int next = reader.next();
   if(next == XMLStreamReader.START_ELEMENT)
       currentElement = reader.getLocalName();
   //System.out.println(currentElement);
}

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