Link to home
Start Free TrialLog in
Avatar of cutie2000
cutie2000

asked on

Save to XML

I have this piece of code.

        public static void SaveXML()
        {
            XmlDocument xmlDoc;
            XmlNode decNode;
            XmlElement rootElement;
            XmlElement level2Element;

            xmlDoc = new XmlDocument();

            // Create and add the XML declaration
            decNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
            xmlDoc.AppendChild(decNode);

            // Create and add the root element Document
            rootElement = xmlDoc.CreateElement("Mail");
            rootElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            rootElement.SetAttribute("xsi:noNamespaceSchemaLocation", "mailValidate.xsd");
            xmlDoc.AppendChild(rootElement);

            // Create a new To element and add it to the Root element
            level2Element = xmlDoc.CreateElement("To");
            level2Element.InnerText = "to@email.com";
            rootElement.AppendChild(level2Element);

            // Create a new Cc element and add it to the Root element
            level2Element = xmlDoc.CreateElement("Cc");
            level2Element.InnerText = "cc@email.com";
            rootElement.AppendChild(level2Element);

            // Create a new Bcc element and add it to the Root element
            level2Element = xmlDoc.CreateElement("Bcc");
            level2Element.InnerText = "bcc@email.com";
            rootElement.AppendChild(level2Element);

            // Create a new From element and add it to the Root element
            level2Element = xmlDoc.CreateElement("From");
            level2Element.InnerText = "from@email.com";
            rootElement.AppendChild(level2Element);

            // Create a new Subject element and add it to the Root element
            level2Element = xmlDoc.CreateElement("Subject");
            level2Element.InnerText = "Subject";
            rootElement.AppendChild(level2Element);

            //Save the XML document
            xmlDoc.Save(@"c:\namevalue.xml");
        }


However, the code is giving me below XML file

<Mail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="mailValidate.xsd">
....

I need to have it as
However, the code is giving me below XML file

<Mail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mailValidate.xsd">
....

Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Here is a little fragment of an example, using the XmlTextWriter and XmlWriterSettings to control the output of the XML document:

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.None;
            settings.OmitXmlDeclaration = false;
            settings.OutputMethod = XmlOutputMethod.Xml;
            settings.CheckCharacters = false;
            settings.CloseOutput = true;
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.Encoding = new UTF8Encoding();
            settings.Indent = true;

            XmlTextWriter writer = XmlTextWriter.Create(fileName, settings);
            writer.WriteStartDocument();

            // <Root>
            writer.WriteStartElement("Root");

            // </Root>
            writer.WriteEndElement();

            writer.WriteEndDocument();

            writer.Close();

Bob
Avatar of cutie2000
cutie2000

ASKER

I need more help.

This is giving me exception.

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.None;
            settings.OmitXmlDeclaration = false;
            settings.CheckCharacters = false;
            settings.CloseOutput = true;
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.Encoding = new UTF8Encoding();
            settings.Indent = true;

            XmlWriter writer = XmlTextWriter.Create(fileName, settings);
            writer.WriteStartDocument();

            // <Root>
            writer.WriteStartElement("Mail");
            writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xmlns", "http://www.w3.org/2001/XMLSchema-instance");

            // </Root>
            writer.WriteEndElement();

            writer.WriteEndDocument();

            writer.Close();
I didn't write the complete XML code for you, so what is the exception?

Bob
Thsi is the exception
System.ArgumentException was unhandled
  Message="Invalid name character in 'xmlns:xsi'. The ':' character, hexadecimal value 0x3A, cannot be included in a name."
  Source="System.Xml"
  StackTrace:
       at System.Xml.XmlWellFormedWriter.CheckNCName(String ncname)
       at System.Xml.XmlWellFormedWriter.WriteStartAttribute(String prefix, String localName, String namespaceName)
       at System.Xml.XmlWriter.WriteAttributeString(String localName, String value)
       at TestConsoleApp.Program.SaveXML(String fileName) in C:\Documents and Settings\hongjun\My Documents\Visual Studio 2005\Projects\CSharpPractice\Test\TestConsoleApp\Program.cs:line 75
       at TestConsoleApp.Program.Main(String[] args) in C:\Documents and Settings\hongjun\My Documents\Visual Studio 2005\Projects\CSharpPractice\Test\TestConsoleApp\Program.cs:line 17
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()


Anyway, this is the result I want.

<?xml version="1.0"?>
<Mail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mailValidate.xsd">
  <To>to@email.com</To>
  <Cc>cc@email.com</Cc>
  <Bcc>bcc@email.com</Bcc>
  <From>from@email.com</From>
  <Subject>Subject</Subject>
  <Body>Body</Body>
</Mail>
System.ArgumentException was unhandled
  Message="Invalid name character in 'xmlns:xsi'.
The XmlTextWriter class has a lot of power, but it is kind of hidden.  The WriteStartElement has 3 overloaded methods.  You would need this form:

WriteStartElement(prefix, localName, ns)

Example:
WriteStartElement("xsi", "Mail", "http://www.w3.org/2001/XMLSchema-instance" );

Bob
This is my code now.
I am unable to get the 2nd attribute written on the Root.
This is the one xsi:noNamespaceSchemaLocation="mailValidate.xsd">

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.None;
            settings.OmitXmlDeclaration = false;
            settings.CheckCharacters = false;
            settings.CloseOutput = true;
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.Encoding = new UTF8Encoding();
            settings.Indent = true;

            XmlWriter writer = XmlTextWriter.Create(fileName, settings);
            writer.WriteStartDocument();

            // <Mail>
//<Mail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mailValidate.xsd">
            writer.WriteStartElement("xsi", "Mail", "http://www.w3.org/2001/XMLSchema-instance");
            //writer.WriteAttributeString("xsi", "Mail", "noNamespaceSchemaLocation", "mailValidate.xsd");

            writer.WriteElementString("To", "to@email.com");
            writer.WriteElementString("Cc", "cc@email.com");
            writer.WriteElementString("Bcc", "bcc@email.com");
            writer.WriteElementString("From", "from@email.com");
            writer.WriteElementString("Subject", "Subject");
            writer.WriteElementString("Body", "This is body");
           
            // </To>
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
Try this:

            writer.WriteAttributeString("noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "mailValidate.xsd");

Bob
bob, thanks a lot

however, i realized something

<xsi:Mail xsi:noNamespaceSchemaLocation="mailValidate.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

seems to be different from

<Mail xsi:noNamespaceSchemaLocation="mailValidate.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">


Notice the extra xsi: generated by the .NET code. If I remove one of the TAG from my generated XML file, VS 2005 does not flag a validation error if I have xsi: in front. If I don't have, VS 2005 correctly flag an error. So I am wondering is it possible to generate without the xsi in front?
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial