我需要提取这些XML-Comments。特别是标准评论。 我是XML-Parsing的新手。我目前正在使用标准的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>
我如何提取评论?
答案 0 :(得分:0)
只需阅读名为&#34;评论&#34;的所有属性我建议通过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]
答案 1 :(得分:0)
如果您不需要将整个XML数据作为java对象并且只需要标准注释属性,则可以使用XPath来获取它:
XPath xpath = XPathFactory.newInstance().newXPath();
return xpath.evaluate("/criteria/criterion/@comment", document);
如果您在字符串中包含XML并且不知道如何将其解析为Document,请查看:How to convert XML (String) to a valid document?
答案 2 :(得分:0)
您还可以使用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 ) );
}
}