简体   繁体   English

使用Java在所有标签名称相同时如何读取xml文件

[英]How to read an xml file when all tag names are same using java

<?xml version="1.0"?>
<test name="test">
    <params>
        <param name="credentials" type="list">
            <item>
                <property name="username" value="abc"/>
                <property name="password" value="cba"/>
            </item>
            <item>
                <property name="username" value="user1"/>
                <property name="password" value="pass1"/>
            </item>
        </param>
        <param name="otherKey" value="singleValue"/>
    </params>

I can have the param tag where one has items or where one is empty. 我可以在一个有项目或一个为空的地方使用param标签。 anyway my question is how to i read the <item> tags using java? 无论如何,我的问题是如何使用Java读取<item>标签? (there maybe more param tags later with more items)one way is taking a nodelist of tag <param> . (稍后可能会有更多带有更多项目的param标签)一种方法是获取标签<param>的节点<param> then taking nodelist of tag <item> for those param which has child nodes and using the getelementbyTag() . 然后为那些具有子节点的参数获取标签<item>的节点列表,并使用getelementbyTag()

is there any other way where the second nodelist can be avoided? 还有其他方法可以避免第二个节点列表吗?

if yes then how?? 如果是,那怎么办?

To avoid the second nodelist item you can specify the index of the nodelist you want. 为了避免第二个节点列表项,可以指定所需节点列表的索引。 which in this case I assume you only want to get the first nodelist. 在这种情况下,我假设您只想获取第一个节点列表。 The code would have to be as follows. 代码必须如下。

String username; 字符串用户名; String password; 字符串密码;

NodeList nList = doc.getElementsByTagName("param") NodeList nList = doc.getElementsByTagName(“ param”)

Node nNode = nList.item(0); 节点nNode = nList.item(0); // This will point to just the first nodelist item //这将仅指向第一个节点列表项

if (nNode.getNodeType() == Node.ELEMENT_NODE) 如果(nNode.getNodeType()== Node.ELEMENT_NODE)
{ Element eElement =(Element) nNode; {Element eElement =(Element)nNode;

  username=eElement.getAttribute("username"); 
 password=eElement.getAttribute("password"); 

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM