XMLStreamWriter 写入包含冒号的标签

XMLStreamWriter write tag containing colon

当我像下面的例子一样在标签名称中使用冒号时,它以错误结束(没有冒号的标签没有问题)。

package test;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class SomeClass{

    public StringWriter test() throws XMLStreamException, TransformerConfigurationException, TransformerException {
        StringWriter stringOut = new StringWriter();
        XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringOut);
        xmlWriter.writeStartDocument("UTF-8", "1.0");
        xmlWriter.writeStartElement("SomeWordHere");
        {
            xmlWriter.writeStartElement("SomeName:enable");//<--- notice the colon
            xmlWriter.writeCharacters("true");
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        xmlWriter.flush();
        xmlWriter.close();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter formattedStringWriter = new StringWriter();

        transformer.transform(new StreamSource(new StringReader(stringOut.toString())), new StreamResult(formattedStringWriter));

        return formattedStringWriter;
    }
}

如何编写仍然包含冒号且不会以错误结尾的标签?

我正在尝试模拟由 LEGO Stud.io 软件生成的 XML 输出 (Collada DAE),有像下面这样的部分包含带冒号的标签名称。

<library_materials>
    <material id="material_id_7" name="SOLID-BLUE">
        <instance_effect url="#effect_id_7-fx" />
        <extra>
            <technique profile="eyesight">
                <ScratchBump:enable> true </ScratchBump:enable>
                <MinScratchStrength:value> 0 </MinScratchStrength:value>
                <MaxScratchStrength:value> 0.2 </MaxScratchStrength:value>
                <BigScratch:enable> true </BigScratch:enable>
                <SmallScratch:enable> true </SmallScratch:enable>
            </technique>
        </extra>
    </material>
</library_materials>

冒号用于命名空间,根据“XML 中的命名空间”规范,它不能用于实体名称。

规范规定:

[Definition: A document is namespace-well-formed if it conforms to this specification. ]

It follows that in a namespace-well-formed document:

  • All element and attribute names contain either zero or one colon;
  • No entity names, processing instruction targets, or notation names contain any colons.

您可以使用一个技巧,将“SomeName”声明为命名空间,如以下问题中所建议的:xml schema validation error "prefix is not bound".

另一方面,“可扩展标记语言”规范指出:

Note:

The Namespaces in XML Recommendation [XML Names] assigns a meaning to names containing colon characters. Therefore, authors should not use the colon in XML names except for namespace purposes, but XML processors must accept the colon as a name character.

如果你改变解析器你可以得到你想要的:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXmlFileDemo {

  public static void main(String[] args) {

    try {
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.newDocument();
      Element rootElement = doc.createElement("SomeName:enable");

      doc.appendChild(rootElement);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);

      StreamResult consoleResult = new StreamResult(System.out);
      transformer.transform(source, consoleResult);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

参考:https://www.w3.org/TR/REC-xml-names/