我有用Java编写的下一个代码:
public class XMLParser {
public static void main(String arg[]) throws Exception {
String message = "<add>\n" +
" <doc>\n" +
" ......................
" <field name=\"imageWidth\" update=\"set\">400</field><field name=\"imageHeight\" update=\"set\">400</field>\n" +
" <field name=\"internalImageUrl\" update=\"set\">https://google.com</field>\n" +
" </doc>\n" +
"</add>";
String s = getUrlValue(message);
System.out.println(s);
}
private static String getUrlValue(String message) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
String urlValue = null;
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(message));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("doc");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("field");
Element line = (Element) name.item(23);
urlValue = line.getTextContent();
}
return urlValue;
}
}
如何获取此属性的值:
field name=\"internalImageUrl\" update=\"set\">https://google.com</field>
我需要获取链接-> "https://google.com"
使用"internalImageUrl"
参数
在我的解决方案中,我使用了:
Element line = (Element) name.item(23);
但是我需要使用循环格式来命名所有名为"field"
的元素,并仅找到"internalImageUrl"