用XmlDocument来格式化XAML文本

用小工具自动生成一段XAML代码,但是自动生成的文本缩进和格式比较乱,想弄得整齐一点。

附上最终的实现代码:

public static string FormatXML(string content)
{
    XmlDocument doc = new XmlDocument();
    XmlReaderSettings settings = new XmlReaderSettings { NameTable = new NameTable() };
    XmlNamespaceManager xmlns = new XmlNamespaceManager(settings.NameTable);
    xmlns.AddNamespace("i", "http://schemas.microsoft.com/xaml/behaviors");
    xmlns.AddNamespace("prism", "http://prismlibrary.com/");
    xmlns.AddNamespace("cg", "clr-namespace:CgdataBase;assembly=CgdataBase.UI");
    xmlns.AddNamespace("cg2", "clr-namespace:CgdataBase");
    XmlParserContext context = new XmlParserContext(null, xmlns, "", XmlSpace.Default);

    using (TextReader tr = new StringReader(content))
    {
        XmlReader reader = XmlReader.Create(tr, settings, context);
        doc.Load(reader);
    }

    StringBuilder stringBuilder = new StringBuilder();
    using (StringWriter stringWriter = new StringWriter(stringBuilder))
    {
        using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
        {
            xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
            xmlTextWriter.Indentation = 4;
            xmlTextWriter.IndentChar = ' ';
            doc.WriteContentTo(xmlTextWriter);
        }
    }

    return stringBuilder.ToString();
}

注意:红字部分的命名空间,根据你XAML代码实际的命名空间使用情况添加,用到的命名空间没有定义的话,转换的时候会报错。

posted @ 2022-09-01 16:31  wzwyc  阅读(146)  评论(0编辑  收藏  举报