Java 将字符串内容转换为 XMLStreamReader
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18733412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert the string content into an XMLStreamReader
提问by user2767404
Hi I would like to know how we can convert the string content which is in the form of XML tag and I need to convert it into XMLStreamReader
嗨,我想知道我们如何转换 XML 标签形式的字符串内容,我需要将其转换为 XMLStreamReader
回答by Jon Skeet
You can use XMLInputFactory.createXMLStreamReader
, passing in a StringReader
to wrap your string.
您可以使用XMLInputFactory.createXMLStreamReader
, 传入 aStringReader
来包装您的字符串。
String text = "<foo>This is some XML</foo>";
Reader reader = new StringReader(text);
XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory()
XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);
回答by reggert
I assume you want to read XML content from a String
via an XMLStreamReader
. You can do that like this:
我假设您想String
通过XMLStreamReader
. 你可以这样做:
public XMLStreamReader readXMLFromString(final String xmlContent)
{
final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
final StringReader reader = new StringReader(xmlContent);
return inputFactory.createXMLStreamReader(reader);
}
回答by Siddh
//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);
}