C#: XmlTextWriter.WriteElementString fails on empty strings?

前端 未结 4 2111
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 12:02

I\'m using XmlTextWriter and its WriteElementString method, for example:

XmlTextWriter writer = new XmlTextWriter(\"filename.xml\",         


        
相关标签:
4条回答
  • 2020-12-06 12:22

    It doesn't fail <Tag/> is just a shortcut for <Tag></Tag>

    0 讨论(0)
  • 2020-12-06 12:34

    Your code should be:

    using (XmlWriter writer = XmlWriter.Create("filename.xml"))
    {
        writer.WriteStartElement("User");
        writer.WriteElementString("Username", inputUserName);
        writer.WriteElementString("Email", inputEmail);
        writer.WriteEndElement();
    }
    

    This avoids resource leaks in case of exceptions, and uses the proper way to create an XmlReader (since .NET 2.0).

    0 讨论(0)
  • 2020-12-06 12:36

    Your output is correct. An element with no content should be written as <tag/>.

    You can force the use of the full tag by calling WriteFullEndElement()

    writer.WriteStartElement("Email");
    writer.WriteString(inputEmail);
    writer.WriteFullEndElement();
    

    That will output <Email></Email> when inputEmail is empty.

    If you want to do that more than once, you could create an extension method:

    public static void WriteFullElementString(this XmlTextWriter writer,
                                              string localName, 
                                              string value)
    {
        writer.WriteStartElement(localName);
        writer.WriteString(value);
        writer.WriteFullEndElement();
    }
    

    Then your code would become:

    writer.WriteStartElement("User");
    writer.WriteFullElementString("Username", inputUserName);
    writer.WriteFullElementString("Email", inputEmail);
    writer.WriteEndElement();
    
    0 讨论(0)
  • 2020-12-06 12:49

    Leaving this here in case someone needs it; since none of the answers above solved it for me, or seemed like overkill.

    FileStream fs = new FileStream("file.xml", FileMode.Create);
    
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    
    XmlWriter w = XmlWriter.Create(fs, settings);
    w.WriteStartDocument();
    w.WriteStartElement("tag1");
    w.WriteStartElement("tag2");
    w.WriteAttributeString("attr1", "val1");
    w.WriteAttributeString("attr2", "val2");
    w.WriteFullEndElement();
    w.WriteEndElement();
    w.WriteEndDocument();
    
    w.Flush();
    fs.Close();
    

    The trick was to set the XmlWriterSettings.Indent = true and add it to the XmlWriter.

    Edit:

    Alternatively you can also use

    w.Formatting = Formatting.Indented;
    

    instead of adding an XmlWriterSettings.

    0 讨论(0)
提交回复
热议问题