0

我有一个看起来像的 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().equals("永久")

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

有谁熟悉这种奇怪的行为?

4

1 回答 1

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#####");
于 2012-09-13T17:19:29.480 回答