如何使用Java提取XML节点中的值列表

时间:2019-03-20 22:29:16

标签: java xml w3c

下面是相关的XML代码:

getSortedData=()=>{
  console.log("hello clicked")
  this.setState({
    sortedData:'companyName'
  })
  // now invoke getdata which will refresh the data:
  this.getData()
}

我有两个<extendedDataElements name="Access" type="noValue"> <children name="item-key" type="string"> <values>00005</values> </children> <children name="access-type" type="string"> <values>Search</values> </children> <children name="key-type" type="string"> <values>Store</values> </children> </extendedDataElements> <extendedDataElements name="Version" type="string"> <values>Core: 3.2.0, Enum: 3.2.3, Log4j1: 3.2.0</values> </extendedDataElements> 对象已成功加载到extendedElements中。我想做的是隔离第二个NodeList对象(我在下面做了),并将<extendedDataElements>标记中的所有字符串提取到<values>中:

List<String>

如何将List<String> valuesList = new ArrayList<String>(); NodeList extendedDataElementsNodeList = commonBaseEvent.getElementsByTagName("extendedDataElements"); //successfully isolates the <extendedDateElements> tag with a list of strings in the <values> Node secondExtendedDataElementNode = extendedDataElementsNodeList.item(1); 标记中用逗号分隔的值列表提取到List中?

简单地说,我如何提取以下XML标记内的所有信息:

<values>

1 个答案:

答案 0 :(得分:1)

获取属性值

String name = secondExtendedDataElementNode.getAttributes().getNamedItem("name").getNodeValue();
String type = secondExtendedDataElementNode.getAttributes().getNamedItem("type").getNodeValue();

首先将逗号分隔的值放入数组

String[] commaSeparatedValue = secondExtendedDataElementNode.selectSingleNode("values").getText().split(",");

然后将这些值添加到列表中,

使用Java8

valuesList = Arrays.stream(commaSeparatedValue).collect(Collectors.toList());

使用Java9

valuesList = List.of(commaSeparatedValue);