Search code examples
c#xmlxmltextwriter

How to add attribute and also elementString via XmlTextWriter?


I am using XmlTextWriter to generate the xml file. Most parts are fine, but encounter the problem to generate bellow part, What I need is:

<site isTrue="false">http://www.example.com</site>

partly main code of mine:

...

using System.Xml;

string filePath = Application.StartupPath + "\\myxml.xml";
     XmlTextWriter myxml = null;
     try
     {
        myxml = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
        myxml.WriteStartDocument();
        // 
        // first 
        myxml.WriteElementString("site","http://www.example.com");
        //
        // second 
        //
        myxml.WriteStartElement("site")
        myxml.WriteAttributeString("isTrue", "false");
     }
    ...

then, for the first method I try , the result is:

<site>http://www.example.com</site>

or if I use second I try ,then the result become:

<site isTrue="false"></site>

any method to add attribute and also innertext? As bellow:

<site isTrue="false">http://www.example.com</site>


Solution

  • myxml.WriteStartElement("site");
    myxml.WriteAttributeString("isTrue", "false");
    myxml.WriteString("http://www.example.com");