是否存在用于可控制XML格式的样式表或Windows命令行工具,特别是每行放置一个属性? [英] Is there a stylesheet or Windows commandline tool for controllable XML formatting, specifically putting attributes one-per-line?

查看:99
本文介绍了是否存在用于可控制XML格式的样式表或Windows命令行工具,特别是每行放置一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找XSLT或命令行工具(或可以做成命令行工具的C#代码等),用于Windows,可以进行XML漂亮打印.具体来说,我想要一种能够一对一地放置属性的功能,例如:

I am searching for an XSLT or command-line tool (or C# code that can be made into a command-line tool, etc) for Windows that will do XML pretty-printing. Specifically, I want one that has the ability to put attributes one-to-a-line, something like:

<Node>
   <ChildNode 
      value1='5'
      value2='6'
      value3='happy' />
</Node>

它不一定完全是这样,但是我想将其用于XML文件,该文件具有带有数十个属性的节点,并将它们分布在多行中可以使它们更易于阅读,编辑和文本差异.

It doesn't have to be EXACTLY like that, but I want to use it for an XML file that has nodes with dozens of attributes and spreading them across multiple lines makes them easier to read, edit, and text-diff.

注意:我认为我的首选解决方案是我可以通过C#方法传递的XSLT工作表,尽管Windows命令行工具也不错.

NOTE: I think my preferred solution is an XSLT sheet I can pass through a C# method, though a Windows command-line tool is good too.

推荐答案

这是一个小的C#示例,您的代码可以直接使用它,也可以将其内置到exe中,并在命令行中将其称为"myexe from.xml to.xml". :

Here's a small C# sample, which can be used directly by your code, or built into an exe and called at the comand-line as "myexe from.xml to.xml":

    using System.Xml;

    static void Main(string[] args)
    {
        XmlWriterSettings settings = new XmlWriterSettings {
            NewLineHandling = NewLineHandling.Entitize,
            NewLineOnAttributes = true, Indent = true, IndentChars = "  ",
            NewLineChars = Environment.NewLine
        };

        using (XmlReader reader = XmlReader.Create(args[0]))
        using (XmlWriter writer = XmlWriter.Create(args[1], settings)) {
            writer.WriteNode(reader, false);
            writer.Close();
        }
    }

样本输入:

<Node><ChildNode value1='5' value2='6' value3='happy' /></Node>

样本输出(请注意,您可以用settings.OmitXmlDeclaration删除<?xml ...):

Sample output (note you can remove the <?xml ... with settings.OmitXmlDeclaration):

<?xml version="1.0" encoding="utf-8"?>
<Node>
  <ChildNode
    value1="5"
    value2="6"
    value3="happy" />
</Node>

请注意,如果您想使用 string 而不是写入文件,只需与StringBuilder交换:

Note that if you want a string rather than write to a file, just swap with StringBuilder:

StringBuilder sb = new StringBuilder();
using (XmlReader reader = XmlReader.Create(new StringReader(oldXml)))
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    writer.WriteNode(reader, false);
    writer.Close();
}
string newXml = sb.ToString();

这篇关于是否存在用于可控制XML格式的样式表或Windows命令行工具,特别是每行放置一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆