2017-04-14 1 views
0

XML 변환을 사용하여 XML을 다른 XML로 변환하는 방법을 설명합니다. 일부 영어 문자가 변환되지 않았습니다.변형 된 XML

원본 XML :

<?xml version="1.0" encoding="UTF-8"?> 
<RR_KeyPersonExpanded_2_0:RR_KeyPersonExpanded_2_0 xmlns:RR_KeyPersonExpanded_2_0="http://apply.grants.gov/forms/RR_KeyPersonExpanded_2_0-V2.0" xmlns:att="http://apply.grants.gov/system/Attachments-V1.0" xmlns:glob="http://apply.grants.gov/system/Global-V1.0" xmlns:globLib="http://apply.grants.gov/system/GlobalLibrary-V2.0" RR_KeyPersonExpanded_2_0:FormVersion="2.0"> 
    <RR_KeyPersonExpanded_2_0:KeyPerson> 
     <RR_KeyPersonExpanded_2_0:Profile> 
     <RR_KeyPersonExpanded_2_0:Name> 
      <globLib:PrefixName>候.</globLib:PrefixName> 
      <globLib:FirstName>Lakshmi</globLib:FirstName> 
      <globLib:MiddleName>AB</globLib:MiddleName> 
      <globLib:LastName>Sørensen</globLib:LastName> 
     </RR_KeyPersonExpanded_2_0:Name> 
     </RR_KeyPersonExpanded_2_0:Profile> 
    </RR_KeyPersonExpanded_2_0:KeyPerson> 
</RR_KeyPersonExpanded_2_0:RR_KeyPersonExpanded_2_0> 

removeemptytags.xsl :

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:strip-space elements="*"/> 
<xsl:output indent="yes" omit-xml-declaration="yes" encoding="UTF-8" method="xml"/> 
<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*[not(descendant-or-self::*[text()[normalize-space()] | @*])]"/> 

</xsl:stylesheet> 

자바 코드 :

public String removeEmptyTags(String xml) { 
    String filteredXML = ""; 
    try (OutputStream bos = new ByteArrayOutputStream();) { 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     StreamSource inputXMLSource = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); 
     StreamSource xsltSource = new StreamSource(getClass().getClassLoader().getResourceAsStream("removeemptytags.xsl")); 
     Transformer transformer = transformerFactory.newTransformer(xsltSource); 

     StreamResult result = new StreamResult(bos); 
     transformer.transform(inputXMLSource, result); 
     bos.flush(); 
     filteredXML = bos.toString(); 
    } catch (Exception e) { 
     logger.log(Level.SEVERE, "Exception while removing empty tags : ", e); 
     throw new ParsingException(e.getMessage()); 
    } 
    return filteredXML; 
} 

OUPUT의 XML :

<RR_KeyPersonExpanded_2_0:RR_KeyPersonExpanded_2_0 xmlns:RR_KeyPersonExpanded_2_0="http://apply.grants.gov/forms/RR_KeyPersonExpanded_2_0-V2.0" xmlns:att="http://apply.grants.gov/system/Attachments-V1.0" xmlns:glob="http://apply.grants.gov/system/Global-V1.0" xmlns:globLib="http://apply.grants.gov/system/GlobalLibrary-V2.0" RR_KeyPersonExpanded_2_0:FormVersion="2.0"> 
<RR_KeyPersonExpanded_2_0:KeyPerson> 
<RR_KeyPersonExpanded_2_0:Profile> 
<RR_KeyPersonExpanded_2_0:Name> 
<globLib:PrefixName>候.</globLib:PrefixName> 
<globLib:FirstName>Lakshmi</globLib:FirstName> 
<globLib:MiddleName>AB</globLib:MiddleName> 
<globLib:LastName>Sørensen</globLib:LastName> 
</RR_KeyPersonExpanded_2_0:Name> 
</RR_KeyPersonExpanded_2_0:Profile> 
</RR_KeyPersonExpanded_2_0:KeyPerson> 
</RR_KeyPersonExpanded_2_0:RR_KeyPersonExpanded_2_0> 

"영어 이외의 단어"가 방금 헛소리의 무리가된다는 것을 알 수 있습니다. xslt에서 "UTF-16"으로 인코딩을 변경하려고 시도하지만 작동하지 않습니다. 누구도 여기에서 같은 문제가 발생합니까?

+1

당신이 UTF-8로 출력의 인코딩을 설정 했습니까? – Compass

답변

2

여러 가지 이상한 문자를 얻으려면 여러 인코딩 문제가있는 것 같습니다.

먼저 xml 문자열 (코드가 표시되지 않음)으로 XML을 읽을 때. UTF-8 인코딩을 지정하는 것을 잊었을지라도 우리가 어떻게 잘못했는지 알 수 없으므로이 코드로는 실제로 도움이되지 않습니다.

둘째, bos.toString()을 호출 할 때. 결과가 String 인 경우 OutputStream을 사용하지 마십시오. StringWriter을 사용하십시오 (아래 코드 참조).

셋째, 문자열을 (코드가 표시되지 않음)에 쓸 때. UTF-8 인코딩을 지정하는 것을 잊어 버렸지 만, 사용자가 어떻게하는지 잘 모르기 때문에 다시 한 번 도움을 줄 수는 없습니다.

public String removeEmptyTags(String xml) { 
    try (StringWriter out = new StringWriter()) { 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     StreamSource inputXMLSource = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); 
     StreamSource xsltSource = new StreamSource(getClass().getClassLoader().getResourceAsStream("removeemptytags.xsl")); 
     Transformer transformer = transformerFactory.newTransformer(xsltSource); 

     transformer.transform(inputXMLSource, new StreamResult(out)); 
     return out.toString(); 
    } catch (Exception e) { 
     logger.log(Level.SEVERE, "Exception while removing empty tags : ", e); 
     throw new ParsingException(e.getMessage()); 
    } 
} 

사실, 인코딩을 XML 라이브러리의 그림을 파일에 /에서 직접 모든 작업을 수행하고, 수 있도록 더 나은 것 :

public void removeEmptyTags(Path inFile, Path outFile) { 
    try (InputStream in = Files.newInputStream(inFile); 
     OutputStream out = Files.newOutputStream(outFile)) { 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     StreamSource xsltSource = new StreamSource(getClass().getClassLoader().getResourceAsStream("removeemptytags.xsl")); 
     Transformer transformer = transformerFactory.newTransformer(xsltSource); 

     transformer.transform(new StreamSource(in), new StreamResult(out)); 
    } catch (Exception e) { 
     logger.log(Level.SEVERE, "Exception while removing empty tags : ", e); 
     throw new ParsingException(e.getMessage()); 
    } 
} 
+0

당신은 정확합니다 !! 여러 번 인코딩했습니다. 결과적으로 결과는 String이어야합니다. byte [] b = StringUtils.toBytesUTF8 (filteredXML)을 사용하여 인코딩을 수행하면됩니다. –