0

My XML is the following

<result cover="http://ia.mediaimdb.com/images      
/M/MV5BMjMyOTM4MDMxNV5BMl5BanBnXkFtZTcwNjIyNzExOA@@._V1._SX54_
CR0,0,54,74_.jpg" title="The Amazing Spider-Man(2012)"year="2012"
director="Marc Webb" rating="7.5"
details="http://www.imdb.com/title/tt0948470"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,
0,54,74_.jpg" title="Spider-Man(2002)" year="2002"director="Sam Raimi"
rating="7.3" details="http://www.imdb.com/title/tt0145487"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ@@._V1._SX54_
CR0,0,54,74_.jpg" title="Spider-Man 3 (2007)" year="2007" director="Sam
Raimi" rating="6.3" details="http://www.imdb.com/title/tt0413300"/>

<result cover="http://i.mediaimdb.
com/images/SF1f0a42ee1aa08d477a576fbbf7562eed/realm/feature.gif" title="
The Amazing Spider-Man 2 (2014)" year="2014" director="Sam Raimi"
rating="6.3" details="http://www.imdb.com/title/tt1872181"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ@@._V1._SX54_
CR0,0,54,74_.jpg" title="Spider-Man 2 (2004)" year="2004" director="Sam
Raimi" rating="7.5" details="http://www.imdb.com/title/tt0316654"/>
</results>

I need to parse this XML file using a parser like saxp and output the result as a json string. I am new to SAXParser. All this while i have been googling out but i cannot simply understand it.

Any ideas?

4

1 回答 1

1

让我用一个简单的例子来解释。

输入 XML:

<Employees>
    <employee name="vels" gender="male"/>
    <employee name="steave" gender="male"/>
</Employees>

使用解析xmlSAXParser

final JSONObject jsonObj = new JSONObject();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        try {
            if (qName.equals("Employees")) {
                // reject root node
                return;
            }
            int len = attributes.getLength();
            HashMap<String, String> map = new HashMap< String, String>();
            for (int i = 0; i < len; i++) {
                String attribName = attributes.getLocalName(i);
                String attribVal = attributes.getValue(i);
                map.put(attribName, attribVal);


            }
            jsonObj.append("employee", map);
        } catch (JSONException ex) {
            // handle excep
        }

    }
};

saxParser.parse("c:/employee.xml", handler);
String jSonOutput = jsonObj.toString();
// process this json outpout
System.out.println(jSonOutput);

输出(手动格式化):

   {"employee":
    [
     {"name":"vels","gender":"male"},
     {"name":"steave","gender":"male"}
    ]
   }

这是Java SAX Parser 和 Java SAX DefaultHandler的一个简单而体面的示例。希望你能继续前进。

于 2012-11-14T11:23:56.513 回答