【问题标题】:getting the localName of XML node获取 XML 节点的 localName
【发布时间】:2012-09-13 17:14:08
【问题描述】:

我有一个看起来像

的 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("permanent")

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

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

【问题讨论】:

  • 您是否尝试获取每个 节点的值?

标签: java android xml-parsing


【解决方案1】:

试试可以试试下面的...

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#####");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多