gpt4 book ai didi

java - 使用 Java 删除 XML 字段中的空格

转载 作者:数据小太阳 更新时间:2023-10-29 02:47:02 24 4
gpt4 key购买 nike

我在删除 xml 数据值字段中的空格时遇到了问题。

例如:

输入

<?xml version="1.0"?>
<ns:myOrder xmlns:ns="http://w3schools.com/BusinessDocument" xmlns:ct="http://something.com/CommonTypes">
<MessageHeader>
<ct:ID>i7 </ct:ID>
<ct:ID>i7 </ct:ID>
<ct:ID>i7 </ct:ID>
<ct:ID>i7 </ct:ID>
<ct:Name> Company Name </ct:Name>
</MessageHeader>
</ns:myOrder>

预期输出:

<?xml version="1.0"?>
<ns:myOrder xmlns:ns="http://w3schools.com/BusinessDocument" xmlns:ct="http://something.com/CommonTypes">
<MessageHeader>
<ct:ID>i7</ct:ID>
<ct:ID>i7</ct:ID>
<ct:ID>i7</ct:ID>
<ct:ID>i7</ct:ID>
<ct:Name>Company Name</ct:Name>
</MessageHeader>
</ns:myOrder>

我试过下面的代码

public static String getTrimmedXML(String rawXMLFilename) throws Exception
{
BufferedReader in = new BufferedReader(new FileReader(rawXMLFilename));
String str;
String trimmedXML = null;
while ((str = in.readLine()) != null)
{
String str1 = str;
if (str1.length()>0)
{
str1 = str1.trim();
if(str1.charAt(str1.length()-1) == '>')
{
trimmedXML = trimmedXML + str.trim();
}
else
{
trimmedXML = trimmedXML + str;
}
}
}
in.close();
return trimmedXML.substring(4);
}

我无法删除这些空格。请让我知道哪里出错了

问候,莫尼什

最佳答案

您可能不想使用替换或全部替换,因为那样它会替换您的 xml 数据中的所有空格。如果要修剪 xml 内容的开始/结束,要么要解析整个 xml,要么使用 xpath 并将其转换回字符串。使用下面的代码。

public static String getTrimmedXML(String rawXMLFilename, String tagName) throws Exception {
// Create xml document object
BufferedReader in = new BufferedReader(new FileReader(rawXMLFilename));
InputSource source = new InputSource(in);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

// Path to the node that you want to trim
NodeList nodeList = (NodeList) xpath.compile("//*[name()='" + tagName + "']").evaluate(document, XPathConstants.NODESET);
for (int index = 0; index < nodeList.getLength(); index++) { // Loop through all nodes that match the xpath
Node node = nodeList.item(index);
String newTextContent = node.getTextContent().trim(); // Actual trim process
node.setTextContent(newTextContent);
}

// Transform back the document to string format.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
return output;
}

关于java - 使用 Java 删除 XML 字段中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520515/

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