gpt4 book ai didi

java - SimpleXML 从特定元素获取内部 XML

转载 作者:行者123 更新时间:2023-12-04 03:42:07 25 4
gpt4 key购买 nike

我在从一个字段中提取值时遇到问题。示例 XML这里:

<Rule id="xccdf_org.cisecurity.benchmarks_rule_4.1.2_Ensure_that_the_kubelet_service_file_ownership_is_set_to_rootroot" selected="false" weight="1.000000" role="full">
<title
xmlns:xhtml="http://www.w3.org/1999/xhtml" xml:lang="en">Ensure that the kubelet service file ownership is set to root:root
</title>
<description
xmlns:xhtml="http://www.w3.org/1999/xhtml" xml:lang="en">
<xhtml:p>Ensure that the
<xhtml:span class="inline_block">kubelet</xhtml:span> service file ownership is set to
<xhtml:span class="inline_block">root:root</xhtml:span>.
</xhtml:p>
</description>
</Rule>

我想获得 description 的全部值字段

我的测试:

@Test
public void ruleTest() throws Exception {
Serializer serializer = new Persister();
File source = new File("E:\\test2.xml");
Rule rule = serializer.read(Rule.class,source);
System.out.println("-----------------------------------------------");
System.out.println("Title: "+rule.title+", Desc: "+rule.description.description);
System.out.println("-----------------------------------------------");
}

和类:

@Root(strict = false, name = "Rule")
public class Rule {
@Element
String title;
@Element(required = false,type = RuleDescription.class)
RuleDescription description;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}
@Root(strict = false, name = "description")
public class RuleDescription {
@Element(name = "p", required = false)
String description;
}

输出是:

-----------------------------------------------
Title: Ensure that the kubelet service file ownership is set to root:root, Desc: Ensure that the
-----------------------------------------------

这意味着SimpleXML只需读取出现在其路径上的第一个标记之前的值和中断。我想获得描述的全部值(value),即: Ensure that the <xhtml:span class="inline_block">kubelet</xhtml:span> service file ownership is set to <xhtml:span class="inline_block">root:root</xhtml:span>.或者没有像 Ensure that the kubelet service file ownership is set to root:root 这样的标签更好但我只需删除标签即可做到这一点。

如果可能的话,谁能给我一个提示?

最佳答案

尝试使用 Simple Framework 的 Convert 类。您可能需要编写自己的 Converter 类来解析上述 XML。示例链接如下所示

SimpleFramwork XML: Element with Inner Text and Child Elements

关于java - SimpleXML 从特定元素获取内部 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65836098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com