获取XML节点的localName

时间:2012-09-13 17:14:08

标签: java android xml-parsing

我有一个看起来像

的xml
<Personnel>
  <Employee type="permanent">
        <Name>Seagull</Name>
        <Id>3674</Id>
        <Age>34</Age>
   </Employee>
  <Employee type="contract">
        <Name>Robin</Name>
        <Id>3675</Id>
        <Age>25</Age>
    </Employee>
  <Employee type="permanent">
        <Name>Crow</Name>
        <Id>3676</Id>
        <Age>28</Age>
    </Employee>
</Personnel>

我正在尝试获取每个节点的名称,然后从那里获取值,但是当我执行以下操作时,我总是得到null或空字符串:

child.getLocalName()。等于( “永久”)

它抛出异常,因为child.getLocalName()为null 我在调试器中检查了孩子,我看到localName =“permanent”

是否有人熟悉这种奇怪的行为?

1 个答案:

答案 0 :(得分:0)

尝试可以尝试使用以下内容...

DOM Parser

SAX Parser

Pull Parser

JAXP AND JAXB

Castor

以下是有关如何使用DOM Parser的代码片段

DocumentBuilderFactory odbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder odb =  odbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xml));
            Document odoc = odb.parse(is);
            odoc.getDocumentElement().normalize ();    // normalize text representation
            System.out.println ("Root element of the doc is " + odoc.getDocumentElement().getNodeName());
            NodeList LOP = odoc.getElementsByTagName("locations");
            int totalPersons =LOP.getLength();
            System.out.println("Total nos of locations:"+totalPersons);

            for(int s=0; s<LOP.getLength() ; s++)
            {
                Node FPN =LOP.item(s);
                if(FPN.getNodeType() == Node.ELEMENT_NODE)
                    {

                    Element latlon = (Element)FPN;                                                                // Change 1

                    NodeList oNameList1 = latlon.getElementsByTagName("featured");                                       // Change 2
                    Element firstNameElement = (Element)oNameList1.item(0);
                    NodeList textNList1 = firstNameElement.getChildNodes();
                    //this.setLocationId(((Node)textNList1.item(0)).getNodeValue().trim());    // Change 3
                    featuredArr = changeToBoolean(((Node)textNList1.item(0)).getNodeValue().trim());                                    // value taken
                    System.out.println("#####The Parsed data#####");
                    System.out.println("featured : " + ((Node)textNList1.item(0)).getNodeValue().trim());            // Change 4
                    System.out.println("#####The Parsed data#####");