Can we force XmlWriter to issue <my-tag></my-tag> rather than <my-tag/>?

你离开我真会死。 提交于 2019-11-28 00:40:29

There is no option setting to do that in .Net. They are the same thing and any parser should be able to handle valid XML.

This worked for me:

writer.WriteStartElement("my-tag");
writer.WriteRaw(someString);
writer.WriteFullEndElement();

WriteEndElement still self closed the tag

If you get the message Extension method can only be declared in non-generic, non-nested static class as the word this may be highlighted, simply create an extension class as shown below:

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

Hope this proves useful :-)

Try this:

x.WriteStartElement("my-tag"); 

//Value of your tag is null

If (<"my-tag"> == "")

{
  x.WriteWhitespace("");
}else
  x.WriteString(my-tag);

x.WriteEndElement();

Have you tried something like this:

if (someString.Length > 0)
{
  someXmlWriter.WriteElementString("my-tag", someString);
}
else
{
  someXmlWriter.WriteStartElement("my-tag");
  someXmlWriter.WriteEndElement("my-tag");
}

Maybe make a utility class with that as a member function.

I use the next code:

if (string.IsNullOrEmpty(myStringValue))
{
   myWriter.WriteStartElement("mytag");
   myWriter.WriteFullEndElement();
}
else
{
   myWriter.WriteElementString("mytag", myStringValue);
}

I just ran into this exact same issue, and while it seems like kind of a hack, this did indeed work and was very unintrusive to the existing code I had to work with.

private static XElement MakeElementLongHand(this XElement rootElem)
{
   rootElem.Value = " ";
   rootElem.Value = string.Empty;
   return rootElem;
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!