gpt4 book ai didi

java - 使用java编辑xml声明编码

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:42 24 4
gpt4 key购买 nike

我正在编辑一个声明中带有原始编码 ASCII 的 xml 文件。在生成的文件中,我希望编码为 UTF-8,以便编写像 åäö 这样的瑞典语字符,但目前我无法做到这一点。

可以在 archivematica wiki 找到与我的文件等效的示例文件。 .

使用上述示例文件的副本运行程序后得到的 SIP.xml 可以通过 this link 访问。 。添加的带有 åäö 文本的标签位于文档的最后。

如下面的代码所示,我尝试在变压器上设置编码,并且还尝试使用 OutputStreamWriter 来设置编码。最后我把原文件中的声明修改为UTF-8,最后åäö就被写出来了。所以问题似乎出在原始文件的编码上。如果我没有记错的话,将声明从 ASCII 更改为 UTF-8 应该不会导致任何问题,问题是,我如何在程序中执行此操作?我可以在将其解析为 Document 对象后执行此操作,还是需要在解析之前执行某些操作?

package provklasser;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
*
* @author
*/
public class Provklass {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
File chosenFile = new File("myFile.xml");
//parsing the xml file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document metsDoc = builder.parse(chosenFile.getAbsolutePath());

Element agent = (Element) metsDoc.getDocumentElement().appendChild(metsDoc.createElementNS("http://www.loc.gov/METS/","mets:agent"));
agent.appendChild(metsDoc.createTextNode("åäö"));

DOMSource source = new DOMSource(metsDoc);

// write the content into xml file
File newFile = new File(chosenFile.getParent(), "SIP.xml");

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

StreamResult result = new StreamResult(newFile);

//Writer out = new OutputStreamWriter(new FileOutputStream("SIP.xml"), "UTF-8");
//StreamResult result = new StreamResult(out);
transformer.transform(source, result);

} catch (ParserConfigurationException ex) {
Logger.getLogger(Provklass.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(Provklass.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Provklass.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Provklass.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Provklass.class.getName()).log(Level.SEVERE, null, ex);
}

}



}

更新:使用 metsDoc.getInputEncoding() 返回 UTF-8,而 metsDoc.getXmlEncoding() 返回 ASCII。如果我在保存新文件后解析它并创建一个新文档,我会得到相同的结果。所以该文档似乎有正确的编码,但 xml 声明不正确。

现在,我在解析 xml 之前将其编辑为文本文件,将上面的解析部分替换为 parseXML(chosenFile.getAbsoutePath()); 并使用以下方法:

private String withEditedDeclaration(String fileName) {
StringBuilder text = new StringBuilder();
try {

String NL = System.getProperty("line.separator");
try (Scanner scanner = new Scanner(new FileInputStream(fileName))) {
String line = scanner.nextLine();
text.append(line.replaceFirst("ASCII", "UTF-8") + NL);
while (scanner.hasNextLine()) {

text.append(scanner.nextLine() + NL);
}
}

} catch (FileNotFoundException ex) {
Logger.getLogger(MetsAdaption.class.getName()).log(Level.SEVERE, null, ex);
}
return text.toString();
}

private void parseXML(String fileName) throws SAXException, IOException, ParserConfigurationException {
String xmlString = withEditedDeclaration(fileName);

//parsing the xml file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
metsDoc = builder.parse(is);
}

它确实有效,但似乎是一个丑陋的解决方案。如果有人知道更好的方法,我将不胜感激。

最佳答案

我遇到了类似的问题,我的 xml 声明最初是:

<?xml version="1.0" encoding="windows-1252"?>

但是在解析为 Document 然后返回为 XML 作为 UTF-8 后,编码保持为 windows-1252,即使字节本身为 UTF-8。我最终发现 TransformerFactory 的实现是 com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl 将其更改为:

org.apache.xalan.processor.TransformerFactoryImpl

来自 Apache Xalan Java 2.7.1 导致 XML 减速中的字符集被正确设置,现在我有:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

关于java - 使用java编辑xml声明编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com