如何将xml转换为java字符串列表
来源:爱站网时间:2021-11-17编辑:网友分享
今天爱站技术小编给大家带来一篇干货,这篇文章主要介绍了如何将xml转换为java字符串列表?需要的朋友可以参考下。希望这篇干货能帮助到你们。
问题描述
我在Java中有一个xml字符串,我需要将其分解为较小的字符串。例如,给出以下内容:
Lokesh Gupta India Alex Gussin Russia David Feezor USA
我如何在没有明显分隔符的情况下进行解析以获取:
string1 = "Lokesh Gupta India "
string2 = "Alex Gussin Russia "
string3 = "David Feezor USA "
任何想法都值得赞赏。谢谢!
思路一:
您可以将XML解析为DOM,迭代根元素的子节点(一旦向XML添加一个,然后将每个元素呈现为XML。
String xml = " \r\n" +
" \r\n" +
" Lokesh \r\n" +
" Gupta \r\n" +
" India \r\n" +
" \r\n" +
" \r\n" +
" Alex \r\n" +
" Gussin \r\n" +
" Russia \r\n" +
" \r\n" +
" \r\n" +
" David \r\n" +
" Feezor \r\n" +
" USA \r\n" +
" ";
// Add missing root element
xml = xml.replaceAll("^()?", "$1") + " ";
// Prepare parser
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document document = domBuilder.parse(new InputSource(new StringReader(xml)));
// Prepare renderer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
// Iterate top-level elements and render them to individual strings
List list = new ArrayList();
for (Node node = document.getDocumentElement().getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
StringWriter buf = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(buf));
String elementXml = buf.toString();
elementXml = elementXml.replaceAll("\\R", " ").trim(); // Eliminate line separators
list.add(elementXml);
}
}
// Print the result
for (String s : list)
System.out.printf("'%s'%n", s);
输出
'Lokesh Gupta India '
'Alex Gussin Russia '
'David Feezor USA '
思路二:
您可以使用StAX进行:
private ArrayList getEmployees(String input) throws XMLStreamException {
ArrayList employees = new ArrayList ();
XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(input));
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLEventWriter xmlEventWriter = null;
StringWriter sw = null;
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if(xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().getLocalPart().equals("employee")) {
sw = new StringWriter();
xmlEventWriter = xmlOutputFactory.createXMLEventWriter(sw);
}
if(xmlEventWriter != null) {
if(xmlEvent.isCharacters() && xmlEvent.asCharacters().isWhiteSpace()) {
continue;
}
xmlEventWriter.add(xmlEvent);
}
if(xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().getLocalPart().equals("employee")) {
xmlEventWriter.close();
employees.add(sw.toString());
xmlEventWriter = null;
sw = null;
}
}
return employees;
}
以上内容就是爱站技术频道小编为大家分享的如何将xml转换为java字符串列表,看完以上分享之后,大家应该都知道怎么操作了吧。