开发者

Formatting XML with tabulation and removing element ending space?

I am trying to do 2 things:

  1. Get the output XML formated with TABULATION instead of spaces.

  2. Remove the ending space it generates for video element.

    " />
    

    to

    "/>
    

I have tried to use

xmlWriter.Formatting = Formatting.Indented;

as well as

IndentChar

but they did not worked for me dont know why.

This is the code I have currently, I would also like to hear advices and suggestion to improve it:

XmlDocument xmlDoc = new XmlDocument();

XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8' standalone='yes'");
xmlWriter.WriteComment(@" This file was made by @author");
xmlWriter.WriteStartElem开发者_高级运维ent("videos");
xmlWriter.Close();

xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
foreach (int myID in ExportListIDs)
{
    XmlElement video = xmlDoc.CreateElement("video");
    root.AppendChild(video);
    video.SetAttribute("videoID", myID.ToString());
}

xmlDoc.Save(filename);


I have managed to solve question 1 with the below code but I still don't know if it is possible to remove the space between " and /> at the end of an element vide question 2.

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        settings.Indent = true;
        settings.IndentChars = "\t";

        XmlWriter writeXML = XmlWriter.Create("test.xml", settings);
        writeXML.WriteStartDocument();
        writeXML.WriteComment(@" This file was made by @author");

        writeXML.WriteStartElement("videos");

        foreach (var item in myList)
        {
            writeXML.WriteStartElement("video");
            writeXML.WriteAttributeString("ID", item.Key.ToString());
            writeXML.WriteAttributeString("Name", item.Value);
                writeXML.WriteStartElement("object");
                writeXML.WriteAttributeString("A", item.Key.ToString());
                writeXML.WriteAttributeString("B", item.Value);
                writeXML.WriteEndElement();
            writeXML.WriteEndElement();
        }

        writeXML.WriteEndElement();
        writeXML.WriteEndDocument();
        writeXML.Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜