简体   繁体   English

如何使用 Javascript 格式化带有换行符的 XML 字符串?

[英]How to format an XML string with line breaks using Javascript?

What I'm trying is to format a string variable, which represents an XML file, with line breaks.我正在尝试格式化一个字符串变量,它代表一个 XML 文件,带有换行符。

// This represents an XML file, but it's not formatted
let xmlStr = "<?xml version="1.0"?><?meta name="test"?><Foo>  <Bar>   <FooBar/>  </Bar></Foo>";

Now, I'm trying to come up with a function to format the string现在,我试图想出一个 function 来格式化字符串

xmlStr = formatXmlStr(xmlStr);
console.log(xmlStr);

The console.log above is supposed to print the following.上面的console.log应该打印以下内容。

<?xml version="1.0"?>
<?meta name="test"?>
<Foo>
  <Bar>
   <FooBar/>
  </Bar>
</Foo>

I found that Javascript offers XMLSerializer , which returns an XML string based on a DOM object.我发现 Javascript 提供XMLSerializer ,它返回一个基于 DOM object 的 XML 字符串。 However...然而...

const docObj = (new DOMParser()).parseFromString(xmlStr, 'text/xml');
const xmlString = (new XMLSerializer()).serializeToString(docObj);

console.log(xmlString);

The resulting xmlString isn't formatted (ie It has no line breaks).生成的xmlString未格式化(即它没有换行符)。

Is it possible to add line breaks to an XML string with Javascript?是否可以使用 Javascript 向 XML 字符串添加换行符?

UPDATE更新

Formatting has to be done without changing tabs (or blank spaces) in the XML string.必须在不更改 XML 字符串中的制表符(或空格)的情况下进行格式化。 This means, for example, solutions posted on this link won't be used because the resulting strings will have different lengths of tabs.这意味着,例如,不会使用此链接上发布的解决方案,因为生成的字符串将具有不同长度的制表符。

If there is no text between the xml-tags like in the example you presented (eg <foo><bar></foo> and not <foo>Some Text</foo> ) one can simply do the following:如果您提供的示例中的xml-tags之间没有文本(例如<foo><bar></foo>而不是<foo>Some Text</foo> ),则可以简单地执行以下操作:

xmlStr.replaceAll(">",">\n")

which results in这导致

<?xml version="1.0"?>
<?meta name="test"?>
<Foo>
  <Bar>
   <FooBar/>
  </Bar>
</Foo>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM