我有以下代码
DocumentBuilderFactory dbFactory_ = DocumentBuilderFactory.newInstance();
Document doc_;
DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);
doc_.getDocumentElement().normalize();
那我可以做
doc_.getDocumentElement();
并获取我的第一个元素,但问题不是 job
,而是 tns:job
。
我知道并尝试使用:
dbFactory_.setNamespaceAware(true);
但这不是我想要的,我需要一些东西来完全摆脱命名空间。
任何帮助将不胜感激, 谢谢,
乔希
最佳答案
使用正则表达式函数。这将解决这个问题:
public static String removeXmlStringNamespaceAndPreamble(String xmlString) {
return xmlString.replaceAll("(<\\?[^<]*\\?>)?", ""). /* remove preamble */
replaceAll("xmlns.*?(\"|\').*?(\"|\')", "") /* remove xmlns declaration */
.replaceAll("(<)(\\w+:)(.*?>)", "$1$3") /* remove opening tag prefix */
.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); /* remove closing tags prefix */
}
关于java - 如何使用 java dom 从 xml 中删除 namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661154/