简体   繁体   中英

Writing to xml from C#

I have a question about writing to xml with C#. I want this kind of structure;

<directory_move>
   <folder_path>
      <source_path>...</source_path>
      ..
      ..
   </folder_path>
   <properties>
      <aaabbcc>....</aaabbcc>
      ..
      ..
   </properties>
</directory_move>

I tried so much but could not obtain what I want. Can you give an advice, how can i do that?

this is my code

        XElement element = new XElement("DIRECTORY_MOVE");

        foreach (string sourceDirName in listArray)
        {
            element.Add(new XElement("SOURCE_PATH", sourceDirName));
        }

        element.Add(new XElement("DESTINATION_PATH", destination));


        if (rdbtnDoLater)
        {
            element.Add(new XElement("RDBTNDOLATER", "checked"));
        }

        if (rdbtnDoImmediately)
        {
            element.Add(new XElement("RDBTNDOIMMEDIATELY", "checked"));
        }

        if (chkIsOverwrite)
        {
            element.Add(new XElement("CHKISOVERWRİTE", "checked"));
        }

        if (chkExitWhenFinish)
        {
            element.Add(new XElement("CHKEXITWHENFINISH", "checked"));
        }

        if (chkFolderQuestion)
        {
            element.Add(new XElement("CHKFOLDERQUESTION", "checked"));
        }

Using Linq to XML

XElement example =
    new XElement("directory_move",
        new XElement("folder_path",
            new XElement("source_path", "..."),
            new XElement("source_path", "...")
        ),
        new XElement("properties",
            new XElement("aaabbcc", ...)
        )
    );

example.WriteToFile(...)

Edit: The issue with your code is that you're adding everything to the root element, so everything will be children of this root.

What you need to do is reproduce the hierarchy, as I did in my example.

XElement root = new XElement("DIRECTORY_MOVE");
XElement folderPath = new XElement("folder_path");

root.Add(folderPath)

foreach (string sourceDirName in listArray)
{
     folderPath.Add(new XElement("SOURCE_PATH", sourceDirName));
}

and so on...

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