读取XML文件中的特定节点-使用JAVA

时间:2018-08-22 22:25:54

标签: java xml

我具有以下XML,并且我想读取节点“输出”中的内容。该“输出”节点位于节点“ test”内部。我可以直到“测试”节点。但是之后,我无法理解。有任何想法吗?我正在使用Java读取文件。

    <?xml version="1.0" encoding="UTF-8"?>
<testrun duration="144040" footerText="Generated by IntelliJ IDEA on 22/08/18 2:45 PM" name="UnitTests">
        <count name="total" value="4"/>
        <count name="error" value="1"/>
        <count name="passed" value="3"/>
        <config nameIsGenerated="true" configId="JUnit" name="UnitTests">
            <module name="Unit-Test"/>
            <option name="PACKAGE_NAME" value=""/>
            <option name="MAIN_CLASS_NAME" value="UnitTests"/>
        </config>
        <root name="UnitTests" location="java:suite://UnitTests">
            <output type="stdout">/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/bin/java -ea -Didea.test.cyclic.buffer.size=1048576 &amp;quot;-javaagent:/Applications/IntelliJ IDEA n-2.8.5.jar&amp;quot; com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 UnitTests
    Process finished with exit code 255
    </output>
        </root>
        <test duration="41937" locationUrl="java:test://UnitTests/signingupUser" name="UnitTests.signingupUser" status="passed">
            <output type="stderr">Aug 22, 2018 2:42:58 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
    INFO: Detected dialect: W3C
    </output>
        </test>
        <test duration="44245" locationUrl="java:test://UnitTests/onBoardingTesting" name="UnitTests.onBoardingTesting" status="error">
            <output type="stderr">Aug 22, 2018 2:43:38 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
    INFO: Detected dialect: W3C
    org.openqa.selenium.TimeoutException: Expected condition failed: waiting for presence of element located by: By.xpath: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.LinearLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.RelativeLayout/android.widget.TextView[1] (tried for 15 second(s) with 500 milliseconds interval)
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:113)
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    </output>
        </test>
        <test duration="32198" locationUrl="java:test://UnitTests/loginSucessfully" name="UnitTests.loginSucessfully" status="passed">
            <output type="stderr">Aug 22, 2018 2:44:24 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
    INFO: Detected dialect: W3C
    </output>
        </test>
        <test duration="25660" locationUrl="java:test://UnitTests/loginInvalidEmail" name="UnitTests.loginInvalidEmail" status="passed">
            <output type="stderr">Aug 22, 2018 2:44:51 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
    INFO: Detected dialect: W3C
    </output>
        </test>
    </testrun>

3 个答案:

答案 0 :(得分:0)

您可以反序列化xml并将其映射到pojo类。将您的xml转换为pojo,可以从http://pojo.sodhanalibrary.com/

获得一些帮助

Jackson pom依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.4</version>
</dependency>

以下是获取测试值的代码和相应的输出:

输出:

ClassPojo [content = Aug 22, 2018 2:42:58 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
            INFO: Detected dialect: W3C
        , type = stderr]
ClassPojo [content = Aug 22, 2018 2:43:38 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
            INFO: Detected dialect: W3C
            org.openqa.selenium.TimeoutException: Expected condition failed: waiting for presence of element located by: By.xpath: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.LinearLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.RelativeLayout/android.widget.TextView[1] (tried for 15 second(s) with 500 milliseconds interval)
            at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:113)
            For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
        , type = stderr]
ClassPojo [content = Aug 22, 2018 2:44:24 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
            INFO: Detected dialect: W3C
        , type = stderr]
ClassPojo [content = Aug 22, 2018 2:44:51 PM io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
            INFO: Detected dialect: W3C
        , type = stderr]

代码:

package yourpackage;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {

    public static void main(String[]args) throws IOException {

        XmlMapper xmlMapper = new XmlMapper();
        String xml = new String(Files.readAllBytes(Paths.get("test.xml")));
        Testrun value = xmlMapper.readValue(xml, Testrun.class);

        for(Test t : value.getTest()) System.out.println(t.getOutput());
    }
}

class Test
{
    private String duration;
    private String locationUrl;
    private String status;
    private String name;
    private Output output;

    public String getDuration ()
    {
        return duration;
    }

    public void setDuration (String duration)
    {
        this.duration = duration;
    }

    public String getLocationUrl ()
    {
        return locationUrl;
    }

    public void setLocationUrl (String locationUrl)
    {
        this.locationUrl = locationUrl;
    }

    public String getStatus ()
    {
        return status;
    }

    public void setStatus (String status)
    {
        this.status = status;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public Output getOutput ()
    {
        return output;
    }

    public void setOutput (Output output)
    {
        this.output = output;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [duration = "+duration+", locationUrl = "+locationUrl+", status = "+status+", name = "+name+", output = "+output+"]";
    }
}


class Output
{
    @JacksonXmlText
    private String content;
    @JacksonXmlProperty(localName = "type")
    private String type;

    public String getContent ()
    {
        return content;
    }

    public void setContent (String content)
    {
        this.content = content;
    }

    public String getType ()
    {
        return type;
    }

    public void setType (String type)
    {
        this.type = type;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [content = "+content+", type = "+type+"]";
    }
}


class Count
{
    private String name;

    private String value;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getValue ()
    {
        return value;
    }

    public void setValue (String value)
    {
        this.value = value;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [name = "+name+", value = "+value+"]";
    }
}

class Root
{
    private String location;

    private String name;

    private Output output;

    public String getLocation ()
    {
        return location;
    }

    public void setLocation (String location)
    {
        this.location = location;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public Output getOutput ()
    {
        return output;
    }

    public void setOutput (Output output)
    {
        this.output = output;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [location = "+location+", name = "+name+", output = "+output+"]";
    }
}


class Module
{
    private String name;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [name = "+name+"]";
    }
}

class Option
{
    private String name;

    private String value;

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getValue ()
    {
        return value;
    }

    public void setValue (String value)
    {
        this.value = value;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [name = "+name+", value = "+value+"]";
    }
}

class Config
{
    private Module module;

    private String name;

    private String nameIsGenerated;

    private Option[] option;

    private String configId;

    public Module getModule ()
    {
        return module;
    }

    public void setModule (Module module)
    {
        this.module = module;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getNameIsGenerated ()
    {
        return nameIsGenerated;
    }

    public void setNameIsGenerated (String nameIsGenerated)
    {
        this.nameIsGenerated = nameIsGenerated;
    }

    public Option[] getOption ()
    {
        return option;
    }

    public void setOption (Option[] option)
    {
        this.option = option;
    }

    public String getConfigId ()
    {
        return configId;
    }

    public void setConfigId (String configId)
    {
        this.configId = configId;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [module = "+module+", name = "+name+", nameIsGenerated = "+nameIsGenerated+", option = "+option+", configId = "+configId+"]";
    }
}

class Testrun
{
    private String duration;

    private String footerText;

    private Count[] count;

    private Root root;

    @JacksonXmlElementWrapper(useWrapping=false, localName = "test")
    private Test[] test;

    private String name;

    private Config config;

    public String getDuration ()
    {
        return duration;
    }

    public void setDuration (String duration)
    {
        this.duration = duration;
    }

    public String getFooterText ()
    {
        return footerText;
    }

    public void setFooterText (String footerText)
    {
        this.footerText = footerText;
    }

    public Count[] getCount ()
    {
        return count;
    }

    public void setCount (Count[] count)
    {
        this.count = count;
    }

    public Root getRoot ()
    {
        return root;
    }

    public void setRoot (Root root)
    {
        this.root = root;
    }

    public Test[] getTest ()
    {
        return test;
    }

    public void setTest (Test[] test)
    {
        this.test = test;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public Config getConfig ()
    {
        return config;
    }

    public void setConfig (Config config)
    {
        this.config = config;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [duration = "+duration+", footerText = "+footerText+", count = "+count+", root = "+root+", test = "+test+", name = "+name+", config = "+config+"]";
    }
}

答案 1 :(得分:0)

使用XPath

try (InputStream xml = new BufferedInputStream(
    Files.newInputStream(pathOfXmlFile))) {

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList outputNodes = (NodeList) xpath.evaluate("//test/output",
        new InputSource(xml), XPathConstants.NODESET);

    int count = outputNodes.getLength();
    for (int i = 0; i < count; i++) {
        Node outputNode = outputNodes.item(i);
        System.out.println(
            "output node content: " + outputNode.getTextContent());
    }
}

答案 2 :(得分:0)

有一个流利的XML阅读器可以实现奇迹。它称为Joox(https://github.com/jOOQ/jOOX) 它允许您执行以下操作:

// Find the order at index four and add an element "paid"
joox(document).find("orders")
              .children()
              .eq(4)
              .append("<paid>true</paid>");

如果不需要,它可以避免创建很多pojo。 因此,您可以使用它和Xpath来实现您的目标。

joox(document).xpath( "//test/output").foreach(/*Do what you need to do*/);