我需要提取这些XML注释。尤其是标准注释。我是XML解析的新手。我目前使用的是标准的Java-XML-Parser javax.xml
<criteria>
<criteria operator="OR" comment="Operation system section">
<extend_definition comment="SUSE Linux Enterprise Server 12 is installed" definition_ref="oval:org.mitre.oval:def:28211"/>
<extend_definition comment="SUSE Linux Enterprise Desktop 12 is installed" definition_ref="oval:org.mitre.oval:def:28148"/>
</criteria>
<criterion comment="update-test-security-0 is earlier than 0:11.2" test_ref="oval:org.mitre.oval:tst:136394"/>
</criteria>
如何提取评论?
发布于 2015-01-19 13:31:49
要只读取名为"comment“的所有属性,我建议通过XMLBeam使用XPath。(披露:我隶属于这个项目。)
public class ReadAttributes {
public static void main(String[] args) {
List<String> comments = new XBProjector().io().stream(ReadAttributes.class.getResourceAsStream("data.xml")).evalXPath("//@comment").asListOf(String.class);
System.out.println(comments);
}
}
此程序打印输出:
[Operation system section, SUSE Linux Enterprise Server 12 is installed, SUSE Linux Enterprise Desktop 12 is installed, update-test-security-0 is earlier than 0:11.2]
发布于 2015-01-19 13:34:14
如果您不需要将整个XML数据作为java对象,而只需要criterion属性,则可以使用XPath获取该属性:
XPath xpath = XPathFactory.newInstance().newXPath();
return xpath.evaluate("/criteria/criterion/@comment", document);
如果您将XML放在字符串中,但不知道如何将其解析为文档,请看一下:How to convert XML (String) to a valid document?
发布于 2015-01-19 13:57:27
您还可以使用JDK的简单XPath特性:
String[] args = new String[]{ "//*[@comment]" };
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
for( String s: args ){
XPathExpression xpExp = xpath.compile( "count("+s+")" );
String res = xpExp.evaluate( source );
System.out.println( s + ": " + res );
int n = Integer.parseInt( res );
for( int i = 1; i <= n; i++ ){
xpExp = xpath.compile( "(" + s + ")[" + i + "]/@comment" );
System.out.println( "comment: " + xpExp.evaluate( source ) );
}
}
https://stackoverflow.com/questions/28025560
复制相似问题