将字符串内容转换为XMLStreamReader

时间:2013-09-11 05:38:19

标签: java

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

3 个答案:

答案 0 :(得分:29)

您可以使用XMLInputFactory.createXMLStreamReader,传入StringReader来换行字符串。

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

答案 1 :(得分:3)

我假设您要通过StringXMLStreamReader读取XML内容。你可以这样做:

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

答案 2 :(得分:1)

//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);
}