views:

360

answers:

0

I am parsing a large xml file. So I am using an XmlReader in combination with XElement instead of XElement.Load().

I have created as XElement object from XmlReader as shown below and here.

static IEnumerable<XElement> StreamRootChildDoc(string uri)
{
    using (XmlReader reader = XmlReader.Create(uri, xmlReaderSettings))
    {
        reader.MoveToContent();
        // Parse the file and display each of the nodes.
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    if (reader.Name == "Child")
                    {
                        XElement el = XElement.ReadFrom(reader) as XElement;
                        if (el != null)
                            yield return el;
                    }
                    break;
            }
        }
    }
}

I want to save this XElement object content in the database as string without the whitespace. None of the below 3 ways work. Just a note, if I load the xml in memory using XElement.Load(), the ToString(SaveOptions.DisableFormatting) works.

<root>  <child></child>  </root> //xml saved in db with whitespace
<root><child></child></root> //want to save as this

XElement.ToString(SaveOptions.DisableFormatting) //
XElement.ToString(SaveOptions.None)
XElement.ToString()

The XmlReaderSettings I am using for the XmlReader object are below. I tried IgnoreWhitespace =true/false with no luck but I cannot set it as true as some elements are skipped.

    XmlReaderSxmlReaderSettings = new XmlReaderSettings();
    xmlReaderSettings.ProhibitDtd = false;
    //xmlReaderSettings.IgnoreWhitespace = true;//cannot use this setting

It works if I parse the XElement object but that defeats the whole purpose of using XmlReader as XElement.Parse() loads the xml in memory.

XElement el = XElement.ReadFrom(reader) as XElement;
XElement.Parse(el.ToString(), LoadOptions.None)

How can I remove the whitespace? Please help. Thanks.