您好我想知道我们如何转换XML标签形式的字符串内容,我需要将其转换为XMLStreamReader
答案 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)
我假设您要通过String
从XMLStreamReader
读取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);
}