这是我的代码:
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();
}
}
我有几个标签&lt; ?PG 1?&gt; ,&lt; ?PG 2?&gt;,&lt; ?PG 3?>表示页码如何从页面标记中获取数据。
答案 0 :(得分:2)
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
答案 1 :(得分:0)
如果您想在代码中阅读Processing Instructions
,请执行以下操作:
NodeList currentPageContent= document.getChildNodes();
for (int i = 0; i < currentPageContent.getLength(); i++) {
Node node = currentPageContent.item(i);
if(node.getNodeType()==Node.PROCESSING_INSTRUCTION_NODE)
System.out.println("the Current Page content is "+ node.getNodeType()+ " : " + node.getNodeName() + " : " + node.getTextContent());
}
希望这有帮助。
答案 2 :(得分:0)
处理指令在DOM( D 项目 O 项目 M odel)中显示为Node.PROCESSING_INSTRUCTION_NODE
。