gpt4 book ai didi

java - XML 解析为对象列表

转载 作者:行者123 更新时间:2023-12-02 07:39:23 27 4
gpt4 key购买 nike

我想使用“SAXParser”将任何 XML 文件解析为“XMLNode”类的对象列表

XMLNode 类

public class XMLNode {

private String nodeName;
private String nodeValue;
private List<XMLNodeAttribute> attributes;
private boolean isParentNode;
private List<XMLNode> childNodes;

//.... getters and setters ....
}

XMLNodeAttribute 类

public class XMLNodeAttribute {

private String name;
private String value;

//.... getters and setters ....

}

请帮助我编写解析器类,它可以将输入作为 XML 文件并输出列表。

提前谢谢您。

我能够编写一些代码..

public class XmlProcesser extends DefaultHandler {

XMLResponse xmlResponse = null;
List<XMLNode> resplist = new ArrayList();
List<XMLNode> temp = new ArrayList();
boolean endtag = false;

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

String elementName = localName;
if ("".equals(elementName)) {
elementName = qName;
}
System.out.println(" Start Ele - " + elementName );

//Each attribute

if (elementName!=null) {
if (attributes!=null) {
for (int pos=0; pos<attributes.getLength(); pos++) {
String name = attributes.getLocalName(pos)==null || attributes.getLocalName(pos).trim().length()==0 ? attributes.getQName(pos) : attributes.getLocalName(pos);
String value= attributes.getValue(pos);
System.out.println(" name - " + name + " value - " + value );
}
}
}

}

@Override
public void characters(char ch[], int start, int length) throws SAXException {

String s = new String(ch, start, length);
System.out.println(" value - " + s );

endtag = false;
}

@Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
endtag = true;

String elementName = localName;
if ("".equals(elementName)) {
elementName = qName;
}
System.out.println(" End Ele - " + elementName );

}
}

最佳答案

您可以使用 JAXB 的 UnmarshallerHandler 来实现此用例:

    JAXBContext jc = JAXBContext.newInstance(XmlNode.clas);
Unmarshaller unmarshaller = jc.createUnmarshaller();
UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(handler);
xr.parse(xml);
XmlNode xmlNode = (XmlNode) handler.getResult();

完整示例

关于java - XML 解析为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11784525/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com