动态读取java中的xml元素和值

时间:2016-09-22 10:11:14

标签: java xml xml-parsing

我试图阅读XML(无论如何,我不知道它的结构,bcz我正在从服务器上阅读flie。),我在SO上搜索了很多。但没有找到任何帮助。

1>我想检索XML的节点名称,从根到文件末尾,孩子的孩子或孩子,直到没有孩子或兄弟姐妹为止。

2 - ;在类似的问题中,我发现他们使用标记名来检索该标记的值,所以我想在其中传递该节点名称以获取值...

是否可以动态执行。或者必须遵循与先前问题相同的结构,例如静态添加标记名以检索值。

在java中执行此操作后,我想创建可执行jar,并希望在欢乐中使用它。

修改 我想找到元素及其值,以便在第一个条件下我循环我的名为masterheader的arraylist包含所有标记名称,并且在第二个循环中我会去从xml中找到节点名称,并且在那两个for循环中我指定了一个条件,如果两者都匹配,那么它获取节点名称并以分隔形式存储一个值,因为我想在csv中转换它

这里,masterheader和childheader是arraylist。 masterheader默认包含所有标头。我们要在childheader中添加nodename,如果两者匹配,那么我们在结果字符串中添加值。 例如masterheader = [employeename, employeesurname, fathername, mobile, salary] 并在childheader = [employeename, mobile, salary] //这是基于xml解析。

for(i=0;i<masterheader.size();i++)
{
    for(j=0;j<childheader.size();j++)
    {
         if((masterheader[i]).equals(childheader[j]))
        {
           //get the value of that node, + ","        
        }
        else
         {
                count++
         }
    }
if(count==childheader.size()){
 //add into result string +null+","  
}
}

2 个答案:

答案 0 :(得分:3)

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

我认为这会有所帮助

答案 1 :(得分:1)

您可以为此目的使用StAX解析器。

XML示例employees.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees count="4">
    <employee>
        <id>2</id>
        <firstName>Jane</firstName>
        <lastName>Doe</lastName>
        <income>20000.0</income>
    </employee>
    <employee>
        <id>3</id>
        <firstName>Alfred</firstName>
        <lastName>Pennyworth</lastName>
        <income>30000.0</income>
    </employee>
    <employee>
        <id>4</id>
        <firstName>Tony</firstName>
        <lastName>Stark</lastName>
        <income>40000.0</income>
    </employee>
    <employee>
        <id>42</id>
        <firstName>Foo</firstName>
        <lastName>Bar</lastName>
        <income>15.0</income>
    </employee>
</employees>

Java代码

try (InputStream stream = new FileInputStream("employees.xml")) {
    XMLInputFactory inputFactory = XMLInputFactory.newFactory();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);

    XMLStreamReader reader = inputFactory.createXMLStreamReader(stream);

    while (reader.hasNext()) {
        switch (reader.next()) {
            case XMLStreamConstants.START_ELEMENT:
                System.out.println("Start " + reader.getName());
                for (int i = 0, count = reader.getAttributeCount(); i < count; i++) {
                    System.out.println(reader.getAttributeName(i) + "=" + reader.getAttributeValue(i));
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                System.out.println("End " + reader.getName());
                break;
            case XMLStreamConstants.CHARACTERS:
            case XMLStreamConstants.SPACE:
                String text = reader.getText();
                if (!text.trim().isEmpty()) {
                    System.out.println("text: " + text);
                }
                break;
        }
    }
}

请注意,您可以轻松修改START_ELEMENT案例,以将标记名称与某个值进行比较。 (如果您只想检查这些元素,可能会忽略任何其他情况。)

输出

Start employees
count=4
Start employee
Start id
text: 2
End id
Start firstName
text: Jane
End firstName
Start lastName
text: Doe
End lastName
Start income
text: 20000.0
End income
End employee
Start employee
Start id
text: 3
End id
Start firstName
text: Alfred
End firstName
Start lastName
text: Pennyworth
End lastName
Start income
text: 30000.0
End income
End employee
Start employee
Start id
text: 4
End id
Start firstName
text: Tony
End firstName
Start lastName
text: Stark
End lastName
Start income
text: 40000.0
End income
End employee
Start employee
Start id
text: 42
End id
Start firstName
text: Foo
End firstName
Start lastName
text: Bar
End lastName
Start income
text: 15.0
End income
End employee
End employees