简体   繁体   中英

How to comment out line by line of a XML file in C# with System.XML

I need to comment and uncomment a XML node with child nodes in a file using System.XML .

Starting XML:

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

Commenting the whole node wouldn't be a problem and easy to achieve like in this example . But my problem is that I've already got some comments inside the node and nested comments aren't allowed per XML rules.

That means I would have to comment out line by line of the XML file so I would not destroy the XML file structure with nested comments.

Desired output:

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

Is it possible to achieve this with System.XML or would I have to do this with regex for example?

Assuming you have this XML well-organised in a file (meaning each node is on its own line, as you presented) you could use this one-liner:

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

This part line.Trim().StartWith("<!--") ? line : $"<!--{line}-->" line.Trim().StartWith("<!--") ? line : $"<!--{line}-->" means if line is a comment (starts with <!-- ) then don't comment it, otherwise, do it.

In my opinion, there is no framework method which provides this functionality. You can read XML file lines and then create new files which has comments for every line as shown in below code.

// 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 + "-->");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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