这是我的代码:
void validate(String fileLocation){
try{
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(fileLocation));
String[] pageContent=new String[100];
for (int i = 0; i < pageContent.length; i++) {
String currentPageContent= document.getElementsByTagName("?PG").item(i).getTextContent();
System.out.println("the Current Page content is "+currentPageContent);
pageContent[i]=currentPageContent;
}
}catch(Exception e){
e.printStackTrace();
}
}
我有几个标记,如 < ?PG 1 ?> 、 < ?PG 2 ?>、< ?PG 3 ?> 表示页码,我如何从页面标记中获取数据。
最佳答案
- 您可以使用递归来遍历
xml
,而无需困惑的嵌套for
循环。 - 您可以将节点类型与
PROCESSING_INSTRUCTION_NODE
进行比较并提取其内容。
XML 示例:
<?xml version="1.0" encoding="UTF-8" ?>
<test>
<ID>Test1</ID>
<TestType name="abc">
<AddressRange start="0x00000000" end="0x0018ffff" />
</TestType >
<TestType name="RAM">
<AddressRange start="0x00400000" end="0x00407fff" />
</TestType >
<?PITarget PIContent?>
<?PISource PISome?>
</test>
代码:
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
FileInputStream path = new FileInputStream("text.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path);
System.out.println();
traverse(document.getDocumentElement());
}
public static void traverse(Node node) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node currentNode = list.item(i);
traverse(currentNode);
}
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
System.out.println("This -> " + node.getTextContent());
}
}
给予,
This -> PIContent
This -> PISome
关于java - 获取 xml 中处理指令标记内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062587/