简体   繁体   中英

I generated classes from an XML schema using xsd. How do I write them back to XML?

The XML schema specifies an index of files. Below is an example of how the XML file should look like.

<?xml version="1.0" encoding="utf-8"?>
<fIndex xsi:schemaLocation="http:address fIndex.xsd" xmlns="address" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <f>
    <foN>SomeDir</foN>
    <fiN>file1.txt</fiN>
  </f>
  <f>
    <foN>SomeDir</foN>
    <fiN>file2.txt</fiN>
  </f>
</fIndex>

I used xsd to create the classes needed for the XML. Then filled in some sample code to match the example above.

class Program
    {
        static void Main(string[] args)
        {
            fileIndexType table = new fileIndexType();

            fileIndexTypeF element1 = new fileIndexTypeF();
            fileIndexTypeF element2 = new fileIndexTypeF();

            element1.fiN = @"C:\SomeDir";
            element1.foN = @"file1.txt";
            element2.fiN = @"C:\SomeDir";
            element2.foN = @"file2.txt";

            fileIndexTypeF[] files = new fileIndexTypeF[2] { element1, element2 };
            table.f = files;
        }
    }

How do I create the above XML file?

You need to serialize the objects.

The XmlSerializer class can be used for this:

XmlSerializer serializer = new XmlSerializer(typeof(fileIndexType));
using(Stream writer = new FileStream(filename, FileMode.Create))
{
  serializer.Serialize(writer, table );
  writer.Close();
}

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