views:

150

answers:

2

I am loading an XML document into an XDocument object, doing a query and then returning the data through a web service as an XmlDocument object.

The code below works fine, but it just seems a bit smelly. Is there a cleaner way to take the results of the query and convert back to an XDocument or XmlDocument?

            XDocument xd = XDocument.Load(Server.MapPath(accountsXml));         

        var accounts = from x in xd.Descendants("AccountsData")
                       where userAccounts.Contains(x.Element("ACCOUNT_REFERENCE").Value)
                       select x;

        XDocument xd2 = new XDocument(
            new XDeclaration("1.0", "UTF-8", "yes"),
            new XElement("Accounts")               
        );

        foreach (var account in accounts)
            xd2.Element("Accounts").Add(account);

        return xd2.ToXmlDocument();
A: 

The fact that you are putting an XDeclaration into your response smells a bit funny to me, too.

Why are you building XML to return through the web service layer? The .NET web services layer, whether you use WCF or ASMX, will do the XML serialization for you.

You can return a strongly-typed object, and it is serialized for you.

Cheeso
@Cheeso - yes the XDeclaration was so I could get the XDocument to validate. This is just for a proof of concept app where I am loading some data from an Xml Document, querying it and then sending it via a web service method. I know I could build up an anonymous type and then have the serialization done for me but the XML document is a big one and I didn't want to do this :)
Ben
A: 

Since this is just for a proof of concept application I wil just live with this code for now. THe live application would be connecting directly to a database so I would not have to pull my data from an xml file, query and then push it out again as xml.

Ben