How do you force explicit tag closing with Linq XML?

前端 未结 4 1121
轻奢々
轻奢々 2020-12-20 13:09

This is the same question as: Explicit Element Closing Tags with System.Xml.Linq Namespace

but I use Net 4.0 and the answers do not work anymore.

The problem i

4条回答
  •  有刺的猬
    2020-12-20 13:45

    I can't reproduce your error. This works as expected in both 4.0 and 3.5 netFX:

    namespace ExplicitXmlClosingTags
    {
        using System.Xml;
        using System.Xml.Linq;
    
        class Program
        {
            static void Main(string[] args)
            {
                const string ElementRoot = "RootElement";
                const string ElementChild = "ChildElement";
                const string AttributeChild = "ChildAttribute";
    
                XDocument xDoc = new XDocument();
                XElement root = new XElement(ElementRoot);
                XElement child = new XElement(ElementChild, string.Empty);
                root.Add(child);
    
                child.SetAttributeValue(AttributeChild, "AttrValue");
                xDoc.Add(root);
    
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.Indent = true;
                using (XmlWriter xw = XmlWriter.Create("out.xml", xws))
                {
                    xDoc.Save(xw);    
                }
            }
        }
    }
    

    producing following content:

    
    
      
    
    

提交回复
热议问题