試試這個。
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Parser {
private static String XPATH_EXPRESSION_STRING = "//Students/Student[not ((name) and (class) and (address))]";
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse("C:\\Users\\NPGM81B\\Desktop\\Students.xml");
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile(XPATH_EXPRESSION_STRING);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
printNode(node, "********");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void printNode(Node rootNode, String spacer) {
System.out.println(spacer + rootNode.getNodeName() + " -> " + rootNode.getNodeValue());
NodeList nl = rootNode.getChildNodes();
for (int i = 0; i < nl.getLength(); i++)
printNode(nl.item(i), spacer + " ");
}
}
Sample XML:
<?xml version="1.0" encoding="UTF-8"?>
<Students>
<Student>
<name>Sample1</name>
<class>1</class>
<address>2525</address>
<email>[email protected]</email>
</Student>
<Student>
<name>Sample2</name>
<class>2</class>
<address>2153</address>
<email>[email protected]</email>
</Student>
<Student>
<email>sa[email protected]</email>
</Student>
</Students>
把所有的學生,經過所有的學生,如果一個沒有名字,沒有班級,沒有地址,那就是那個學生。 – Shadov
@阿倫。我已經創建了一個示例來說明您的要求。讓我知道如果你需要更多的細節 – mhasan
@mhasan。非常感謝..!!現在我得到了我真正想要的東西... – Arun