在Java中解析GML时出现错误字符
我正在使用org.w3c.dom包来解析gml模式(http://schemas.opengis.net/gml/3.1.0/base/) 当我解析gmlBase.xsd模式并将其保存回时,BagType复杂类型中GeometryCollections周围的引号字符将转换为错误字符(请参见下面的代码) 我解析或保存xml的方式是否有问题,或者模式中是否有关闭的内容 谢谢 柯蒂斯在Java中解析GML时出现错误字符,java,xml,schema,gml,Java,Xml,Schema,Gml,我正在使用org.w3c.dom包来解析gml模式(http://schemas.opengis.net/gml/3.1.0/base/) 当我解析gmlBase.xsd模式并将其保存回时,BagType复杂类型中GeometryCollections周围的引号字符将转换为错误字符(请参见下面的代码) 我解析或保存xml的方式是否有问题,或者模式中是否有关闭的内容 谢谢 柯蒂斯 public static void main(String[] args) throws IOException {
public static void main(String[] args) throws IOException
{
File schemaFile = File.createTempFile("gml_", ".xsd");
FileUtils.writeStringToFile(schemaFile, getSchema(new URL("http://schemas.opengis.net/gml/3.1.0/base/gmlBase.xsd")));
System.out.println("wrote file: " + schemaFile.getAbsolutePath());
}
public static String getSchema(URL schemaURL)
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(IOUtils.toString(schemaURL.openStream()))));
Element rootElem = doc.getDocumentElement();
rootElem.normalize();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream xmlOutStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(xmlOutStream);
transformer.transform(source, result);
return xmlOutStream.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
我怀疑这句话:
Document doc = db.parse(new InputSource(
new StringReader(IOUtils.toString(schemaURL.openStream()))));
我不知道IOUtils.toString
在这里做了什么,但可能它假设了一种特定的编码,而没有考虑XML声明
为什么不直接使用:
Document doc = db.parse(schemaURL.openStream());
同样,您的
FileUtils.writeStringToFile
似乎没有指定字符编码。。。它使用哪种编码,以及为什么在StreamResult
中使用编码?您已经掌握了一些信息。如果我将系统属性“file.encoding”更改为“UTF-8”,那么一切都会按预期工作。但是,如果不设置“file.encoding”属性,我就不知道如何做。我的应用程序将是已部署的web应用程序。我没有能力更改系统属性。@Curtis:你不应该依赖任何固定的编码。您是否特别需要将模式作为字符串获取?我想将模式写入一个文件,以便以后可以查看它。然而,在编写之前,我可能需要修改一些xml元素,这就是为什么我首先使用DocumentBuilder解析它。如果不依赖编码,我如何做到这一点?原始代码没有指定任何编码,文件无效。@Curtis:在文档格式中修改它,然后直接将其写入流。我想我现在明白你的意思了。我使用xmlOutStream.toByteArray()而不是xmlOutStream.toString(),它确实维护了编码(无需指定或更改任何编码设置)。谢谢(不要使用apachefileutils,这也会把事情搞砸)。