read XML from a webservice remove a child element based on the value of its attribute it and write it back to the - c#

Lets say The following is my xml input that I receive from my webservice using this code:
string url = txtURL.Text;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
XmlDocument doc = new XmlDocument();
doc.Load(rep.GetResponseStream());
rep.Close();
now I have the following xml document in the "doc"
<note>
<parent_element>
<child_element attribute_1="1">
<inner_element> first Text </inner_element>
</child_element>
<child_element attribute_1="2">
<inner_element> second Text </inner_element>
</child_element>
</parent_element>
</note>
Now I want to remove the first child element based on its attribute value. So if the attribute value of the child element is "1" then I want to delete "child_element" and all of its child elements. so my final result should look like this:
<note>
<parent_element>
<child_element attribute_1="2">
<inner_element> second Text </inner_element>
</child_element>
</parent_element>
</note>
Once I have removed the element, I would write it back to the webservice. I know i am asking for a lot, but havent been able to figure it out so far.
I would include my code, but since I am a newbie to xml manipulation, i think that will be of no use (sad face). Any help or direction will be appreciated.
Thank you guys.

First of all: doc.load(txtURL.Text) is enough to load the XML from a remote location.
You can delete a node like this:
XmlDocument doc = new XmlDocument();
doc.Load(filename);
//Select node that needs to be deleted
XmlNode node = doc.SelectSingleNode("/note/parent_element/child_element[#attribute_1 = '1']");
node.ParentNode.RemoveChild(node);
How you write all that back to your web application depends on what it is expecting. I will attach one example that POSTs a XML file against a RESTful web service
WebRequest req = WebRequest.Create(updateURL);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.Default.GetBytes(xmldoc);
req.ContentLength = bytes.Length;
Stream data = req.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();

Related

Transform XML returned from a web request using XLST

I see several questions that are close to this but none exactly cover it:
How to apply an XSLT Stylesheet in C#
XSLT Transform of XML using Xml data from a web form
How to transform an xml structure generated from a request to a web services
I can cobble something together from these but I worry I am passing it through too many steps to be efficient.
What I currently have is this, to read XML from a HTTP web request:
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string xml = streamReader.ReadToEnd();
This was before the need to apply an XLST transform was needed. Now I have a (possibly null) XslCompiledTransform object.
So I want to add a block like:
if(transform != null)
{
xml = transform.Transform(xml);
}
Clearly this isn't possible as written. I see StringReaders and XmlReaders can be created but is it inefficient to get my xml as a string and then push it back into another object? Can I use my stream or streamReader objects directly to support the same basic flow, but with optional transformation?
Personally I'd use the XmlDocument.Load() function to load the XML from the URL, without using WebRequest in this case.
You can pass the XmlDocument Straight to XSLCompiledTransform.Transform() then.
XmlDocument doc = new XmlDocument();
doc.Load(url);
if (transform != null)
{
XmlDocument tempDoc = new XmlDocument();
using (XmlWriter writer = tempDoc.CreateNavigator().AppendChild())
{
transform.Transform(doc, writer);
}
doc = tempDoc;
} //Use your XmlDocument for your transformed output

How Can I Read The XML

I'm getting geografic info from a webservice.
I'm trying to parse the return data for hours, but have been getting no where.
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
XDocument document = XDocument.Parse(result, LoadOptions.None);
i got this
document <html>
<body>
<state>Apure</state>
<municipality>RĂ“MULO GALLEGOS</municipality>
<parish>URBANA ELORZA</parish>
<street>La Trinidad De Arauca</street>
</body>
</html> System.Xml.Linq.XDocument
I try
document.Elements("state")
document.Descendants("body")
document.GetElementsByTagName("state");
But nothing.
I'm sure there is a simple way of do something so basic.
I'm seriously considering convert that to a string and do the parsing myself.
Aditional consideration:
The fields include it in the result is variable.
Because some info doesnt have all fields.
Ok, I make a change.
I read a XElement instead of a XDocument;
XElement sitemap = XElement.Parse(result, LoadOptions.None);
foreach (var bodyElement in sitemap.Elements("body"))
{
foreach (var fieldElement in bodyElement.Elements())
{
Console.WriteLine(fieldElement.Name);
Console.WriteLine(fieldElement.Value);
}
}
Probably there is a way to skip the first foreach, but still looking for it.
#Jonesy line works but that mean I have to know the fields names. This way i just create the info for the values I got.

Loading xdocument gets 'root element missing'

I'm trying to load some xml into a XDocument. The XML data is provided by the city of Philadelphia, so that's not something I can change. I had a similar query before, which worked just fine. The xml response also seems to hold up in online XML validators, so how can I load it into my XDocument?
Here's the xml request
Here's my code, slightly simplified (first two lines taken and modified from another function).
string searchString = "http://services.phila.gov/PhillyApi/Data/v1.0/permits?$expand=locations&$filter=(issued_datetime%20gt%20Datetime%272012-12-01%27%20and%20issued_datetime%20le%20Datetime%272014-07-18%27)%20and%20(substringof(%27MAJOR%27,permit_type_code)%20or%20substringof(%27MINOR%27,permit_type_code)%20or%20substringof(%27PARIA%27,permit_type_code)%20or%20substringof(%27NEWCON%27,permit_type_code)%20or%20substringof(%27ENTIRE%27,permit_type_code))";
XDocument xResult = MakeRequest(searchString);
public static XDocument MakeRequest(string requestUrl)
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// This line causes the error 'root element missing'
XDocument xDoc = XDocument.Load(response.GetResponseStream());
return (xDoc);
}

No elements found when parsing eBay's api result xml

I'm trying to search eBay via C# and XML. I can see that I'm getting a valid XML response, by writing out the XML to a string, but cannot parse it using C# - I just keep getting told that there are no elements.
Here's my code, with my appname key removed:
string xmldata = "<?xml version='1.0' encoding='utf-8'?>";
xmldata += "<findItemsAdvancedRequest xmlns='http://www.ebay.com/marketplace/search/v1/services'>";
xmldata += "<keywords>sneakers</keywords>";
xmldata += "<categoryId>1</categoryId>";
xmldata += "<descriptionSearch>false</descriptionSearch>";
xmldata += "<paginationInput>";
xmldata += "<entriesPerPage>5</entriesPerPage>";
xmldata += "</paginationInput>";
xmldata += "</findItemsAdvancedRequest>";
string url = "http://svcs.ebay.com/services/search/FindingService/v1";
//Create a HttpWebRequest object
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//Convert xml string to a byte array
byte[] postDataBytes = Encoding.ASCII.GetBytes(xmldata);
//Set the Method property
req.Method = "POST";
//Set the ContentType property of the "HttpWebRequest"
req.ContentType = "text/xml;charset=UTF-8";
req.Headers.Add("X-EBAY-SOA-SERVICE-NAME", "FindingService");
req.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsAdvanced");
req.Headers.Add("X-EBAY-SOA-SERVICE-VERSION", "1.4.0");
req.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-GB");
req.Headers.Add("X-EBAY-SOA-REQUEST-DATA-FORMAT", "XML");
req.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME: **********************");
//Set the ContentLength property of the "HttpWebRequest"
req.ContentLength = postDataBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
XDocument myXML = XDocument.Load(resp.GetResponseStream());
IEnumerable<XElement> elements = myXML.Root.Element("searchResult").Elements("item");
I've tried various combinations of the last line - getting the Count of the Descendants for example, but always get variations of 'no matching elements' messages. I know that the results are there: when I set a breakpoint and look at the myXML variable in Visual Studio, the XML all seems to be in the Root.
The problem is that the returned XML uses XML namespaces, while your query doesn't. Assuming the namespace is the same as the one in the XML you are sending to the server, this would work:
XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";
var elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");

How to consume an HTTP webservice in Asp.net?

I want to generate html content based on a result returned by http url.
http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=X1-ZWz1c239bjatxn_5taq0&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA
This page will give you some XML results. I want to convert to use that XML to generate HTML. I am not getting any idea where to start? Would someone offer any guidelines or sample code for asp.net?
For details: http://www.zillow.com/howto/api/GetDeepSearchResults.htm
To fetch the data you can use the HttpWebRequest class, this is an example I have to hand but it may be slightly overdone for your needs (and you need to make sure you're doing the right thing - I suspect the above to be a GET rather than a POST).
Uri baseUri = new Uri(this.RemoteServer);
HttpWebRequest rq = (HttpWebRequest)HttpWebRequest.Create(new Uri(baseUri, action));
rq.Method = "POST";
rq.ContentType = "application/x-www-form-urlencoded";
rq.Accept = "text/xml";
rq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Encoding encoding = Encoding.GetEncoding("UTF-8");
byte[] chars = encoding.GetBytes(body);
rq.ContentLength = chars.Length;
using (Stream stream = rq.GetRequestStream())
{
stream.Write(chars, 0, chars.Length);
stream.Close();
}
XDocument doc;
WebResponse rs = rq.GetResponse();
using (Stream stream = rs.GetResponseStream())
{
using (XmlTextReader tr = new XmlTextReader(stream))
{
doc = XDocument.Load(tr);
responseXml = doc.Root;
}
if (responseXml == null)
{
throw new Exception("No response");
}
}
return responseXml;
Once you've got the data back you need to render HTML, lots and lots of choices - if you just want to convert what you've got into HTML with minimal further processing then you can use XSLT - which is a question all on its own. If you need to do stuff with it then the question is too vague and you'll need to be more specific.
Create a xsl stylesheet, and inject the stylesheet element into the resulting xml from teh page

Categories

Resources