2013-02-07 41 views
0

我想遍歷XML文件中的所有子節點。如果驗證值失敗,那麼我想將/ clone節點追加到一個新的xml文檔中。對以下代碼的任何建議?迭代和驗證DOM節點 - java

for(Node childNode = node.getFirstChild(); childNode!=null;) 
{ 
    Node nextChild = childNode.getNextSibling(); 
    //validate here and append or 
    //clone to new xml file if false 
    childNode = nextChild; 
} 

我創建了驗證器實例,它確實驗證了每個節點。我如何找出哪個節點失敗(true,false)然後追加。我可以使用布爾值進行失敗驗證,然後追加到新文檔中嗎?

// creating a Validator instance 
Validator validator = schema.newValidator(); 
Validator.validate(new DOMSource(childNode)) ; 
+0

我創建了驗證器實例,它確實驗證了每個節點。 如何找出哪些節點失敗(true,false),然後追加。我可以使用布爾值進行失敗驗證,然後追加到新文檔中嗎? //創建Validator實例 Validator validator = schema.newValidator(); Validator.validate(new DOMSource(childNode)); – mick

+0

請點擊「編輯」按鈕更新您的問題,並在您的評論中包含信息,以便其他人可以輕鬆看到它。你會以這種方式得到更好的回覆=) – maerics

回答

-1

Ecnountered同樣的問題,發現這裏 http://blog.bigpixel.ro/2011/08/validating-xml-node-against-a-xsd-schema/

驗證所有功勞博客

編輯的作者的解決方案:Sry基因,很着急。

這裏的想法是:javax.xml.validation.Validator在整個文檔上工作,而不是在單個節點上工作。因此,節點首先轉換爲其字符串表示形式,然後轉換爲可評估的文檔。

雖然博客條目主要顯示了Dom2String轉換,但我會在這裏向您展示更有趣的部分,其中針對XSD的驗證發生(與博客的作者有點不同,因爲我不想捕捉所有可能的例外)

static public boolean validateNodeAgainstXSD(Node node, String schemaFile) throws TransformerException, 
    IOException { 
    // check if the arguments are valid 
    if (node == null || schemaFile == null || schemaFile.isEmpty()) { 
     logger.error("Invalid Argument(s)"); 
     return false; 
    } 

    //Create Stream from the XSD file and an empty Schema object 
    InputStream istream = new FileInputStream(new File(schemaFile)); 
    String schemaLang = "http://www.w3.org/2001/XMLSchema"; 
    SchemaFactory factory = SchemaFactory.newInstance(schemaLang); 
    Schema schema; 
    try { 
     // configure the Schema objeczt with your XSD 
     schema = factory.newSchema(new StreamSource(istream)); 
     // get your Validator 
     Validator validator = schema.newValidator(); 
     logger.debug("Node content to be validated: {0}", domNodeToString(node)); 
     //get your Node as Stream 
     StringReader r = new StringReader(domNodeToString(node)); 
     //throws SAXException iff the validation fails 
     validator.validate(new StreamSource(r)); 
    } catch (SAXException e) { 
     logger.warn("SAXException caught " + e.getMessage()); 
     return false; 
    } 
    return true; 

} 
+2

而不是隻是鏈接到博客(鏈接過時等),它會更有幫助回答這個問題,然後引用博客作爲源 – beresfordt