[英]How to get value of XML tag with different attributes?
I need to get value from XML tag with different attributes. 我需要从具有不同属性的XML标记中获取价值。
For example: XML 例如:XML
<metaData>
<parameter name="HTTP-Method">POST</parameter>
<parameter name="HTTP-URI">/loan/test?testArg=1234&id=5555555</parameter>
<parameter name="HTTP-Version">HTTP/1.1</parameter>
<parameter name="Host">localhost:7002</parameter>
<parameter name="Content-Length">0</parameter>
<parameter name="Origin">chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop</parameter>
</netaData>
here I need to get a value of tag "parameter" with an attribute "HTTP-Method" and another one with attribute "HTTP-URI" 在这里,我需要获取带有属性“ HTTP-Method”的标记“ parameter”的值和具有属性“ HTTP-URI”的另一个值
This what I do: 我该做什么:
NodeList nodeList = document.getElementsByTagName("parameter");
for (int i = 0, size = nodeList.getLength(); i < size; i++) {
Element elem = (Element) nodeList.item(i);
Here I got all the parameter tags. 在这里,我得到了所有参数标签。 How can I get the specific one? 如何获得特定的?
This block of code 此代码块
for (int i = 0; i < nodeList.getLength(); i++) {
Element elem = (Element) nodeList.item(i);
String attribute = elem.getAttribute("name");
if ("HTTP-Method".equals(attribute) || "HTTP-URI".equals(attribute)) {
System.out.println(elem.getTextContent());
}
}
will print 将打印
POST
/loan/test?testArg=1234&id=5555555
With the library Dynamics & Java 8 this can be done pretty directly. 借助Dynamics &Java 8库,可以直接完成此操作。 Using Streams and lambdas we can walk through the xml in a fairly natural way. 使用Streams和lambda,我们可以以相当自然的方式遍历xml。
XmlDynamic example = new XmlDynamic("<metaData>" +
"<parameter name=\"HTTP-Method\">POST</parameter>" +
"<parameter name=\"HTTP-URI\">/loan/test?testArg=1234&id=5555555</parameter>" +
"</metaData>");
String uri = example.get("metaData")
.children()
.filter(parameter -> parameter.get("@name").asString().equals("HTTP-URI"))
.findAny()
.map(parameter -> parameter.asString())
.get(); // assuming this value is always there
Or perhaps to be a little more defensive, if the xml is less guaranteed to have what we expect. 或者,如果不那么保证xml具有我们期望的内容,则可能更具防御性。
Optional<String> uri = example.get("metaData")
.children()
.filter(param -> param.get("@name").maybe().asString().orElse("").equals("HTTP-URI"))
.findAny()
.map(param -> param.asString());
You can add the library to your maven project with 您可以使用以下方法将库添加到您的Maven项目中:
<dependency>
<groupId>com.github.alexheretic</groupId>
<artifactId>dynamics</artifactId>
<version>2.3</version>
</dependency>
You can use the Scilca XML Progression Package available at GitHub. 您可以使用GitHub上提供的Scilca XML Progression Package。
List<Node> list = document.getElementsWithAttribute(new Attribute("Name", "HTTP-URI", true); // True cause the value of the attribute should be same
Node need = list.get(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.