所以我有一个格式为
的XML文件 <Document DocID="doc1" DocType="Message" MimeType="message">
<Tags>
<Tag TagName="#From" TagDataType="Text" TagValue="Jim"/>
<Tag TagName="#To" TagDataType="Text" TagValue="hello@so.com
<Tag TagName="#Subject" TagDataType="Text" TagValue="This Subject"/>
</Tags>
<Files>
<File FileType="Text">
<ExternalFile FilePath="text_000" FileName="hello.txt"/>
</File>
</Files>
<Locations>
<Location>
<LocationURI>allen-p\'Sent Mail</LocationURI>
</Location>
</Locations>
</Document>
我想更多地关注标签:
<Tag TagName="#TO" TagDataType="Text" TagValue="Jim"/>
说我想找到所有标有TagName "#TO"
的标签,我希望得到相应的TagValue
(在这种情况下,它将是&#34; Jim&#34;)。< / p>
我需要为TagName="#TO"
的每个标记执行此操作。并获得TagValue
。
我怎么能用Java做到这一点?
答案 0 :(得分:0)
如果要使用DOM来解析XML文档,可以尝试这样做:
public static void main(String[] args) {
List<String> toTags = parseTags("#To");
toTags.forEach(tag -> System.out.println(tag));
}
public static List<String> parseTags(String tag){
List<String> tags = new ArrayList<>();
Document doc = getXmlDocument("src/test/Document.xml");
Element root = doc.getDocumentElement();
NodeList tagNode = root.getElementsByTagName("Tag");
for(int i = 0; i < tagNode.getLength(); i++){
Node n = tagNode.item(i);
NamedNodeMap attributes = n.getAttributes();
attributes.getLength();
Node tagName = attributes.getNamedItem("TagName");
if(tagName.getNodeValue().equals(tag)){
Node tagValue = attributes.getNamedItem("TagValue");
tags.add(tagValue.getNodeValue());
}
}
return tags;
}
private static Document getXmlDocument(String path){
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document doc = domBuilder.parse(new File(path));
return doc;
} catch (SAXException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
答案 1 :(得分:0)
使用xpath获取所需的值,检查下面的代码,这将获得TagName中的TagValue =“#To”
String query = "/Document//Tags/Tag[contains(@TagName,'To')]/@TagValue";
String inputXML = FileUtils.readFileToString(new File("yourfile.xml"));
InputSource source = new InputSource(new ByteArrayInputStream(inputXML.getBytes("utf-8")));
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(source);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String toValue = xpath.evaluate(query, document);
System.out.println(toValue);
还有一件事,你需要添加apache commons-io作为依赖来运行上面的代码。