【问题标题】:How to comment out line by line of a XML file in C# with System.XML如何使用 System.XML 在 C# 中逐行注释掉 XML 文件
【发布时间】:2019-01-11 18:15:10
【问题描述】:

我需要使用System.XML 在文件中注释和取消注释带有子节点的 XML 节点。

开始 XML:

<?xml version="1.0" encoding="utf-8"?>
    <test>
    <!--comment...-->    
        <childTest>
            <childchildTest>5<childchildTest/>
        </childTest>
    </test>

评论整个节点不会成为问题,并且很容易实现,就像在这个example 中一样。但我的问题是节点内已经有一些 cmets,并且每个 XML 规则都不允许嵌套 cmets。

这意味着我必须逐行注释掉 XML 文件,这样我就不会使用嵌套的 cmets 破坏 XML 文件结构。

期望的输出:

<?xml version="1.0" encoding="utf-8"?>
<!--    <test> -->
    <!--comment...-->    
<!--        <childTest> -->
<!--           <childchildTest>5<childchildTest/> -->
<!--        </childTest> -->
<!--    </test> -->

是否可以使用 System.XML 来实现这一点,或者我是否必须使用正则表达式来实现这一点?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    假设您在文件中组织良好的 XML(这意味着每个节点都在自己的行上,如您所介绍的),您可以使用这个单行:

    File.WriteAllLines("path to new XML file", File.ReadAllLines("path to XML file").Select(line => line.Trim().StartsWith("<!--") ? line : $"<!--{line}-->"));
    

    这部分line.Trim().StartWith("&lt;!--") ? line : $"&lt;!--{line}--&gt;"表示如果line是评论(以&lt;!--开头)则不要评论,否则,做。

    【讨论】:

    • 这忽略了 OP 的“嵌套”cmets 问题。
    • @RandRandom 啊,你是对的!更正答案:)
    • 应该修剪线条,以防出现前导空格。
    • 我只打算用StartsWith 进行检查,因为它现在会导致错误。
    • 现在我可以开始抱怨你的代码不尊重多行 cmets,但对于 OP 来说可能就足够了。 :)
    【解决方案2】:

    在我看来,没有提供此功能的框架方法。 您可以读取 XML 文件行,然后为每一行创建具有 cmets 的新文件,如下面的代码所示。

    // Create a string array with the lines of text
    string[] lines = File.ReadAllLines(path-of-file);
    
    // Write the string array to a new file named "ouput.xml".
    using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath,"output.xml"))) {
        foreach (string line in lines)
            outputFile.WriteLine("<!--" + line + "-->");
    }
    

    【讨论】:

    • 这忽略了 OP 的“嵌套”cmets 问题。
    • 感谢您的回答,这种方法可以根据我的需要进行修改。
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 2014-01-08
    • 1970-01-01
    • 2018-07-18
    • 2011-06-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多