Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this string :

<test>I am a test</test>

But when I write it in my xml file, and open it, I have this :

&lt;test&gt;I am a test&lt;/test&gt;

I don't know how to use the good formatting. I tried HttpUtility.HtmlDecode, but it does not solve my problem.

Do you have an idea on this ?

Edit : Sorry for not having posted my code before, I thought my problem was really really trivial. Here is a sample I just wrote that resumes the situation (I'm not at work anymore so I don't have the original code) :

XmlDocument xmlDoc = new XmlDocument();
doc.LoadXml("<root>" +
            "<test>I am a test</test>" +
            "</root>");
string content = xmlDoc.DocumentElement.FirstChild.InnerXml;

XDocument saveFile = new XDocument();
saveFile = new XDocument(new XElement("settings", content));
saveFile.Save("myFile.xml");

I just want my xml file content looks like my original string, so in my case the file would normally contain :

<settings>
    <root>
        <test>I am a test</test>
    </root>
</settings>

Right ? But instead, I have something like :

<settings>&lt;root&gt;&lt;test&gt;I am a test&lt;/test&gt;&lt;/root&gt;
</settings>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
284 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do something along the lines of Converting XDocument to XmlDocument and vice versa to convert the root element of your XmlDocument to an XElement and then add it to your XDocument:

public static class XmlDocumentExtensions
{
    public static XElement ToXElement(this XmlDocument xmlDocument)
    {
        if (xmlDocument == null)
            throw new ArgumentNullException("xmlDocument");

        if (xmlDocument.DocumentElement == null)
            return null;

        using (var nodeReader = new XmlNodeReader(xmlDocument.DocumentElement))
        {
            return XElement.Load(nodeReader);
        }
    }        
}

And then use as follows:

        // Get legacy XmlDocument
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml("<root>" +
                    "<test>I am a test</test>" +
                    "</root>");

        // Add its root element to the XDocument
        XDocument saveFile = new XDocument(
            new XElement("settings", xmlDoc.ToXElement()));

        // Save
        Debug.WriteLine(saveFile.ToString());

And the output is:

<settings>
  <root>
    <test>I am a test</test>
  </root>
</settings>

Note this avoids the overhead of converting the XmlDocument to an XML string and re-parsing it from scratch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...