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.
Related
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);
}
I trying to convert JSON output into XML. Unfortunately I get this error:
JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.
This is what I up to now created.
string url = string.Format("https://graph.facebook.com/{0}?fields=posts.fields(message)&access_token={1}", user_name, access_token);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
jsonOutput = reader.ReadToEnd();
Console.WriteLine("THIS IS JSON OUTPUT: " + jsonOutput);
}
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonOutput);
Console.WriteLine(doc);
And this is my JSON output:
{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}
How can I solve this problem?
Despite the fact your JSON provided in the question is not complete, you have multiple properties at the top level as indicated by the exception. You have to define the root for it to get valid XML:
var doc = JsonConvert.DeserializeXmlNode(jsonOutput, "root");
EDIT: In order to print out your XML with indentation you can use XDocument class from System.Xml.Linq namespace: XDocument.Parse(doc.InnerXml).
I thought it's worth linking to the Documentation for turning xml to json and the other way around.
The guys are right..
// To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
You can do JSON-to-XML also by using the .NET Framework (System.Runtime.Serialization.Json):
private static XDocument JsonToXml(string jsonString)
{
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(jsonString)))
{
var quotas = new XmlDictionaryReaderQuotas();
return XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(stream, quotas));
}
}
DeserializeXmlNode returns XDcument.
If needed XNode use FirstNode.
//string jsonOutput="{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}";
var myelement= JsonConvert.DeserializeXmlNode(jsonOutput, "myelement").FirstNode;
Your shared JSON is invalid please go through http://jsonformatter.curiousconcept.com/ and validate your JSON first.
Yourt JSON should look like:
{
"id":"108013515952807",
"posts":{
"data":[
{
"id":"108013515952807_470186843068804",
"created_time":"2013-05-14T20:43:28+0000"
},
{
"message":"TEKST",
"id":"108013515952807_470178529736302",
"created_time":"2013-05-14T20:22:07+0000"
}
]
}
}
Adding on #jwaliszko's answer, converting json to XDocument:
XDocument xml = JsonConvert.DeserializeXNode(json);
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();
I have a problem for parsing a rss feed using c#.
I used to use this method to load the feed.
XDocument rssFeed = XDocument.Load(#url);
But, when I notice when the feed has a xml-stylesheet this method crashes saying the xml is not well formated...
Here's a rss feed that contains this tag
http://www.channelnews.fr/accueil.feed?type=rss
What would be the best way to parse any rss feed using c#?
Thanks for your help
This code works for me
static XDocument DownloadPage()
{
var req = (HttpWebRequest)WebRequest.Create("http://www.channelnews.fr/accueil.feed?type=rss");
req.UserAgent = "Mozilla";
using(var response = req.GetResponse())
using(var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
return XDocument.Load(reader);
}
Note, that if you omit setting UserAgent, then response will contain string 'DOS' that is defnintly not xml :)
This one works nicer:
XDocument xdoc = XDocument.Load("http://pedroliska.wordpress.com/feed/");
var items = from i in xdoc.Descendants("item")
select new
{
Title = i.Element("title").Value
};
So now you can access the rss titles by doing a loop or something like:
items[0].Title
And just the code is pulling the title from the rss feed, you can pull the description, link, pubDate, etc.
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