2013-01-07 57 views
1

爲了使對XML文件中的一些變化,我用下面的代碼:Transformer對象自動添加命名空間的子元素

public boolean run() throws Exception { 
    XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) { 

    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { 
      if(AddRuleReq&& qName.equalsIgnoreCase("cp:ruleset")) 
      { 
      attributeList.clear(); 
      attributeList.addAttribute(uri, localName, "id", "int", Integer.toString(getNewRuleId())); 
      super.startElement(uri, localName, "cp:rule", attributeList); 
      attributeList.clear(); 
      super.startElement(uri, localName, "cp:conditions", attributeList); 
      super.startElement(uri, localName, "SOMECONDITION", attributeList); 
      super.endElement(uri, localName, "SOMECONDITION"); 
      super.endElement(uri, localName, "cp:conditions"); 
      super.startElement(uri, localName, "cp:actions", attributeList); 
      super.startElement(uri, localName, "allow", attributeList); 
      super.characters(BooleanVariable.toCharArray(), 0, BooleanVariable.length()); 
      super.endElement(uri, localName, "allow"); 
      super.endElement(uri, localName, "cp:actions"); 
      } 
     } 
}; 
    Source source = new SAXSource(xr, new InputSource(new StringReader(xmlString))); 
    stringWriter = new StringWriter(); 
    StreamResult result = new StreamResult(stringWriter); 
    Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); 
    transformer.transform(source, result); 
    return stringWriter.toString(); 
} 

我已經貼上它的一小部分,它的作品。但幾乎沒有什麼區別。

我有什麼期望看到的是:

<cp:rule id="1"> 
    <cp:conditions> 
    <SOMECONDITION/> 
    </cp:conditions> 
    <cp:actions> 
    <allow> 
    true 
    </allow> 
    </cp:actions> 
</cp:rule> 

我看到的是:

<cp:rule id="1"> 
    <cp:conditions> 
    <SOMECONDITION xmlns="urn:ietf:params:xml:ns:common-policy"/> 
    </cp:conditions> 
    <cp:actions> 
    <allow xmlns="urn:ietf:params:xml:ns:common-policy"> 
    true 
    </allow> 
    </cp:actions> 
</cp:rule> 

的處理XML也無效根據我的架構和不可用的下一個時間。

我的問題是,如何防止將這些命名空間添加到子元素中(如在本例中,< SOMECONDITION xmlns =「urn:ietf:params:xml:ns:common-policy」/>)?

在此先感謝..

回答

1

您呼籲allow標籤使用錯誤的參數startElement方法,我很驚訝你的XML處理器沒有爲此拋出一個錯誤:

super.startElement(uri, localName, "allow", attributeList); 

這裏uricp:ruleset元素的命名空間uri,它是作爲參數獲得的,localNameruleset元素的名稱。正確的應該是以下內容,使用一個空字符串作爲命名空間uri,併爲qname和本地名稱匹配值。

super.startElement("", "allow", "allow", attributeList); 

這同樣適用於你的其他startElement/endElement調用,而不是

super.startElement(uri, localName, "cp:rule", attributeList); 

應該

super.startElement(uri, "rule", "cp:rule", attributeList); 
+0

非常感謝你,你已經改正了一個巨大的誤解。 – user1873190

相關問題