开发者

Ways of parsing an XML document to Java objects [duplicate]

开发者 https://www.devze.com 2023-03-03 22:34 出处:网络
This question already has answers here: 开发者_运维知识库 Java to XML conversions? [closed] (9 answers)
This question already has answers here: 开发者_运维知识库 Java to XML conversions? [closed] (9 answers) Closed 5 years ago.

I am looking for different ways of parsing an XML document to Java objects.

I have an XML document, I need to parse this XML document to extract the elements and parse them in to Java objects.

Could you please recommend the following?

  • different approaches
  • productive parser tools for Java


try the solution given in this url http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/


Personally I'll use Groovy program a simple XML parser of the XML document using XmlSlurper and returns a map as an interface.

Or just use the Groovy to return the value

class XmlParseHelper {
    private def xmlNode;

    private String elementName


    public XmlParserHelper(String elementName, String xml){
        this.elementName = elementName
        xmlNode = new XmlSlurper().parseText(xml)
    }

    public int getTotalRows(){
        return xmlNode.table.find{it.@name == elementName}.row.size()
    }


    public String getValue(String columName, int index){
        return xmlNode.table.find{it.@name == elementName}.row[index].column.find{it.@name == columnName}.toString()
    }
}

and can be used like this

//xml is the string of the xml
XmlParseHelper xmlParseHelper = new XmlParseHelper ("mytable", xml);

        for(int i = 0; i < XmlParseHelper .getTotalRows(); i++){
            String code= xmlParseHelper.getValue("code", i);
            String name= xmlParseHelper.getValue("name", i);
.....
     }

This was for an specific XML, but well: it's a different approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消