JAVA-Parse-XML
我有以下XML:JAVA-Parse-XML,java,xml,Java,Xml,我有以下XML: <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope> <soapenv:Body> <response> <note identifier="4719b11c-230e-4533-b1a5-76ac1dc69ef7" hash="956F3D94-A8B375ED-BA15739F-387B4F5E-75C6ED82
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope>
<soapenv:Body>
<response>
<note identifier="4719b11c-230e-4533-b1a5-76ac1dc69ef7" hash="956F3D94-A8B375ED-BA15739F-387B4F5E-75C6ED82" dat_prij="2016-09-27T23:06:20+02:00"/>
<item uid="9f9cb5fb-75e6-4a2f-be55-faef9533d9ff-ff" active="true"/>
</response>
</soapenv:Body>
</soapenv:Envelope>
使用DOM:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));
Document doc = builder.parse(is);
NodeList nList = doc.getElementsByTagName("item");
Node namedItem = nList.item(0).getAttributes().getNamedItem("uid");
System.out.println(namedItem.getNodeValue());
使用SAX:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("item")) {
System.out.println(attributes.getValue("uid"));
}
}
};
saxParser.parse(new InputSource(new StringReader(response)), handler);
您可能想阅读一些关于XML、DOM和SAX的教程:
或者您可以使用正则表达式和一些字符串替换:
Pattern pattern = Pattern.compile("uid=\"[^\"]*\"");
Matcher matcher = pattern.matcher(response);
if(matcher.find()) {
String attr = matcher.group();
attr = attr.replace("\"", "");
attr = attr.replace("uid=", "");
System.out.println(attr);
}
注:
您的XML不是有效的SOAP消息。它缺少一些名称空间声明-未声明soapenv前缀,并且您的元素和属性未定义。@CosmeLopes-我为问题添加了其他信息
Pattern pattern = Pattern.compile("uid=\"[^\"]*\"");
Matcher matcher = pattern.matcher(response);
if(matcher.find()) {
String attr = matcher.group();
attr = attr.replace("\"", "");
attr = attr.replace("uid=", "");
System.out.println(attr);
}