使用 Java 从 xml 文件中提取值

Extract values from xml file using Java

这是我的回复包含 XML 文件,我想从这个 xml 回复

中检索 bEntityID="328"
  <?xml version="1.0" encoding="UTF-8"?>
<ns2:aResponse xmlns:ns2="http://www.***.com/F1/F2/F3/2011-09-11">
   <createBEntityResponse bEntityID="328" />
</ns2:aResponse>

我正在尝试这样做,但得到 null

    System.out.println("bEntitytID="+XmlPath.with(response.asString())
   .getInt("aResponse.createBEntityResponse.bEntityID"));

关于从此回复中获得 BEntityID 的任何建议?

虽然我不建议使用以下方法使用 Regex 获取元素值,但如果您实在太想获取元素值,请尝试以下代码:

public class xmlValue {
    public static void main(String[] args) {
        String xml = "<ns2:aResponse xmlns:ns2=\"http://www.***.com/F1/F2/F3/2011-09-11\">\n" +
                "   <createBEntityResponse bEntityID=\"328\" />\n" +
                "</ns2:aResponse>";
        System.out.println(getTagValue(xml,"createBEntityResponse bEntityID"));
    }
    public static  String  getTagValue(String xml, String tagName){
         String [] s;
         s = xml.split("createBEntityResponse bEntityID");
         String [] valuesBetweenQuotes = s[1].split("\"");
         return  valuesBetweenQuotes[1];
    }
    }

Output: 328

注意:更好的解决方案是使用XML解析器

这将获取第一个标签值:


public static String getTagValue(String xml, String tagName){
    return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}

另一种方法是使用 JSoup:

Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); //parse the whole xml doc
for (Element e : doc.select("tagName")) {
    System.out.println(e); //select the specific tag and prints
}

我认为最好的方法是将 xml 反序列化为类似 的 pojo,然后获取值

entityResponse.getEntityId();

我尝试使用相同的 XML 文件,并能够使用以下代码获取 bEntityId 的值。希望对你有帮助。

@Test
public void xmlPathTests() {
    try {
    File xmlExample = new File(System.getProperty("user.dir"), "src/test/resources/Data1.xml");
    String xmlContent = FileUtils.readFileToString(xmlExample);

    XmlPath xmlPath = new XmlPath(xmlContent).setRoot("aResponse");

    System.out.println(" Entity ::"+xmlPath.getInt(("createBEntityResponse.@bEntityID"))); 

    assertEquals(328, xmlPath.getInt(("createBEntityResponse.@bEntityID")));
    } catch (Exception e) {
        e.printStackTrace();
    }
}