I am using the web service API of a third party application to 开发者_C百科search for data via my web application.
There is a contacts API and a client API. The contacts table holds the ID of the client, but not the name. To search for and display a contact and also display the name of the client I need to call both API's.
What is the best way of joining the two resultant XML files? I am using .Net 4.0.
I'd do it quick and dirty:
XDocument
.Parse(
"<bigDoc>"
+XDocument.Parse("<a><b/></a>").Root
+XDocument.Parse("<c><d/></c>").Root
+"</bigDoc>")
But you'll probably run into all sorts of namespace issues that will be difficult to resolve. As said below, why not write code to query both docs?
The best way is not to join the XML files at all, unless you actually need the data in XML format.
There is no way to join the XML files as they are, so you would have to parse both files, join the data, and then create a new XML file from that. I assume that you are just after the data, so the last step would be superflous.
You can for example use LINQ to XML to get the data from the XML files and join it. Example:
XElement contacts = XElement.Parse(contactsXml);
XElement clients = XElement.Parse(clientsXml);
var contactsWithClients =
from contact in contacts.Elements("Contact")
join client in clients.Elements("Client")
on contact.Attribute("ClientId").Value equals client.Attribute("Id").Value
into grp
select new {
ContactName = contact.Attribute("Name").Value,
ClientName = grp.Single().Attribute("Name").Value
};
If it's a web service you're calling, make sure the return values resolve to class definitions rather than plain old XML. On the client-code side, define a container class to hold these 2 classes. The container class can then be XML serialized/deserialized according to your needs, and the resulting XML will be properly formed.
精彩评论