2016-02-10 1 views
0

Мне нужно обновить файл content.xml в файле odt. Я хочу получить то же содержимое файла без пробелов от элементов и без разрыва строки.XSL-преобразование не записывает пространство имен перед элементами

Я попытался использовать транскрипцию xsl с объектом Transformer в Java, и он частично работает. Например, имея простой ODT, которую content.xml является следующее:

<?xml version="1.0" encoding="utf-8" ?> 
<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.2"> 
    <office:font-face-decls> 
     <style:font-face style:name="Courier New" style:font-family-generic="modern" style:font-pitch="fixed" svg:font-family="'Courier New'" /> 
    </office:font-face-decls> 
    <office:automatic-styles> 

    </office:automatic-styles> 
    <office:body> 
     <office:text> 
      <text:p text:style-name="Title">TODO supply a title</text:p> 
      <text:p text:style-name="Text_20_body">TODO write content</text:p> 
      <text:h text:style-name="Heading_20_1" text:outline-level="1">My First Heading</text:h> 
      <text:p text:style-name="First_20_paragraph">My first paragraph.</text:p> 
     </office:text> 
    </office:body> 
</office:document-content> 

Я написал этот XSL файл, чтобы удалить все разрывы строк, пробелы между элементами, так что я хочу получить то же самое содержание XML Serialize в одной строке.

<?xml version="1.0" encoding="ISO-8859-15" ?> 
<xsl:stylesheet version="1.0" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:xalan="http://xml.apache.org/xslt" 
       xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" 
       xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" 
       xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" 
       xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" 
       xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" 
       xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" 
       xmlns:xlink="http://www.w3.org/1999/xlink" 
       xmlns:dc="http://purl.org/dc/elements/1.1/" 
       xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" 
       xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" 
       xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" 
       xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" 
       xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" 
       xmlns:math="http://www.w3.org/1998/Math/MathML" 
       xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" 
       xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" 
       xmlns:ooo="http://openoffice.org/2004/office" 
       xmlns:ooow="http://openoffice.org/2004/writer" 
       xmlns:oooc="http://openoffice.org/2004/calc" 
       xmlns:dom="http://www.w3.org/2001/xml-events" 
       xmlns:xforms="http://www.w3.org/2002/xforms" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns="urn:oasis:names:tc:opendocument:xmlns:office:1.0" 
       extension-element-prefixes="office style text" 
> 
    <xsl:output method="xml" encoding="ISO-8859-15" indent="no"/> 
    <xsl:strip-space elements="*" /> 


    <xsl:template match="@*|node()|comment()|processing-instruction()|text()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()|comment()|processing-instruction()|text()" /> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

Я отступ = «нет» и стрип-космических элементов = «*» не иметь identation, но теперь моя проблема заключается в пространствах имен. XML, который я получаю с помощью этого XSL заключается в следующем:

<?xml version="1.0" encoding="ISO-8859-15"?><document-content xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.2"><font-face-decls><font-face style:font-family-generic="modern" style:font-pitch="fixed" style:name="Courier New" svg:font-family="'Courier New'"/></font-face-decls><automatic-styles/><body><text><p text:style-name="Title">TODO supply a title</p><p text:style-name="Text_20_body">TODO write content</p><h text:outline-level="1" text:style-name="Heading_20_1">My First Heading</h><p text:style-name="First_20_paragraph">My first paragraph.</p></text></body></document-content> 

Это в одной строке, как я хочу, но элементы не имеет префикса пространства имен. Обратите внимание, что это не происходит с атрибутами, которые имеют правильные пространства имен.

В xsl, указанном мной для сопоставления узлов, комментариев и атрибутов, пространства имен в элементе <xsl:stylesheet> и префиксы расширения-элемента, передающие список разрешенных пространств имен. Если я удалю добавочные элементы-префиксы, ничего не изменится.

код Java, который используется объект Transformer является следующее:

public void serializeXML(String filePath, String destinationPath) throws Exception { 
    File xmlFile = new File(filePath); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = dBuilder.parse(xmlFile); 
    doc.normalizeDocument(); 

    DOMSource domSource = new DOMSource(doc); 
    TransformerFactory transformerFactory = TransformerFactory.newInstance(); 

    InputStream is = XMLSerializer.class.getClassLoader().getResourceAsStream("identer.xsl"); 

    Transformer transformer = transformerFactory.newTransformer(new StreamSource(is)); 

    StringWriter sw = new StringWriter(); 
    StreamResult sr = new StreamResult(sw); 
    transformer.transform(domSource, sr); 

    Result result = new StreamResult(new FileOutputStream(new File(destinationPath))); 

    transformer.transform(domSource, result); 

    LOGGER.info(sw.toString()); 
} 

Я объявляю объект Transformer, передавая ему InputStream файла XSL. Я не задаю никаких свойств, потому что я объявляю все (на мой взгляд) необходимым в файле xsl, и после этого я преобразовываю документ, сохраняя результат в файле и печатая его с помощью регистратора.

Может кто-нибудь мне помочь?

спасибо.

+1

Как вы настраиваете/настраиваете свой трансформатор? – robert

+1

Ваш код работает правильно с использованием этого онлайн-трансформатора: http://www.freeformatter.com/xsl-transformer.html – robert

+1

http://xsltransform.net/bnnZWD отлично работает для меня. Что касается расширений-элементов-префиксов, этот атрибут каким-либо образом не имеет отношения к копированию пространств имен, он просто указывает элементы в пространстве имен, которые будут обрабатываться как инструкции элемента расширения. –

ответ

0

Я решил, благодаря пользователям, которые отвечают на мой вопрос.

Я пересмотрел свой код, поэтому XSL сейчас:

<xsl:output method="xml" encoding="ISO-8859-15" indent="no"/> 
<xsl:strip-space elements="*" /> 

<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

И тогда я упростил код Java, которые используют трансформатор:

public void serializeXML(String filePath, String destinationPath) throws Exception { 

     TransformerFactory factory = TransformerFactory.newInstance(); 
     InputStream is = XMLSerializer.class.getClassLoader().getResourceAsStream("identer.xsl"); 
     Source xslt = new StreamSource(is); 
     Transformer transformer = factory.newTransformer(xslt); 

     Source text = new StreamSource(new File(filePath)); 
     transformer.transform(text, new StreamResult(new File(destinationPath))); 

    }