首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何转换xml并保留换行符?

要转换 XML 并保留换行符,可以使用一些编程语言的内置库或第三方库。以下是一些常见编程语言的示例代码:

  1. Python:
代码语言:python
代码运行次数:0
复制
import xml.etree.ElementTree as ET

xml_string = "<root><element1>value1</element1<element2>value2</element2></root>"
root = ET.fromstring(xml_string)

for element in root.iter():
    element.text = element.text.replace('\n', '')

xml_string_no_newlines = ET.tostring(root).decode()
print(xml_string_no_newlines)
  1. JavaScript:
代码语言:javascript
复制
const xml2js = require('xml2js');

const xmlString = '<root><element1>value1</element1<element2>value2</element2></root>';

xml2js.parseString(xmlString, (err, result) => {
  const newResult = JSON.parse(JSON.stringify(result).replace(/\n/g, ''));
  const newXmlString = xml2js.Builder().buildObject(newResult);
  console.log(newXmlString);
});
  1. Java:
代码语言:java
复制
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
    public static void main(String[] args) throws Exception {
        String xmlString = "<root><element1>value1</element1<element2>value2</element2></root>";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xmlString));
        Document doc = dBuilder.parse(is);

        replaceNewlines(doc.getDocumentElement());

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        String xmlStringNoNewlines = writer.getBuffer().toString().replaceAll("\n", "");
        System.out.println(xmlStringNoNewlines);
    }

    private static void replaceNewlines(Element element) {
        NodeList childNodes = element.getChildNodes();
        for (int i = 0; i< childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                childNode.setNodeValue(childNode.getNodeValue().replaceAll("\n", ""));
            } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                replaceNewlines((Element) childNode);
            }
        }
    }
}

这些示例代码将读取 XML 字符串,删除所有换行符,并将结果输出为新的 XML 字符串。请注意,这些示例代码仅适用于简单的 XML 结构。对于更复杂的 XML 结构,可能需要使用更高级的 XML 解析库。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券