2011-12-13 58 views
12

我有一個像獲取XML和將XML元素轉換爲文檔對象並獲取已創建的元素值和屬性的情況如何將字符串轉換爲Java中的DOM文檔對象?

這是我試圖將字符串轉換爲DOM文檔對象

String xmlString = " <r><e>d</e></r>"; 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = factory.newDocumentBuilder(); 
org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
DOMSource source = new DOMSource(document); 
StreamResult result = new StreamResult(new StringWriter()); 
transformer.transform(source, result); 
String str1 = result.getWriter().toString(); 
System.out.println(str1); 

但這種情況下是有效的唯一元素,而屬性 我們能做些什麼,如果

String xmlString = "<element attribname="value" attribname1="value1"> pcdata</element>" 

我們使用雙引號的ATT ribute值「值」。編譯器顯示錯誤

如果有任何xml編碼器和解碼器可以處理這種情況,

+0

它應該很好的屬性 - 你看到了什麼行爲? –

回答

5

要麼逃避雙引號\

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>" 

,或者使用單引號代替

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>" 
2
 public static void main(String[] args) { 
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+ 
          "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+ 
          "<role>Developer</role><gen>Male</gen></Emp>"; 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder; 
     try 
     { 
      builder = factory.newDocumentBuilder(); 
      Document doc = builder.parse(new InputSource(new StringReader(xmlStr))); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
1
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type. 

即使XML結構很複雜,這對我來說也很好。

請確保您的xmlString對XML有效,注意轉義字符應該在前面添加「\」。

主要問題可能不是來自屬性。

相關問題