Here is a sample soap response from my SuperDuperService:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<MyResponse xmlns="http://mycrazyservice.com/SuperDuperService">
<Result>32347</Result>
</MyResponse>
</soap:Body>
</soap:Envelope>
For some reason when I try to grab the Descendant or Element of "Result" I get null. Does it have something to do with the Namespace? Can someone provide a solution to retrieve Result from this?
You might want to try something like this:
string myNamespace= "http://mycrazyservice.com/SuperDuperService";
var results = from result in yourXml.Descendants(XName.Get("MyResponse", myNamespace))
select result.Element("Result").value
Don't have VS on this laptop so I can't double check my code, but it should point you in the right direction using LINQ to SQL.
to extend Justin's answer with tested code with a return that excpects a boolean and that the response and result start with the method name (BTW - a surprise is even thought the XML element does not show the NS it requires it when parsing):
private string ParseXml(string sXml, string sNs, string sMethod, out bool br)
{
br = false;
string sr = "";
try
{
XDocument xd = XDocument.Parse(sXml);
if (xd.Root != null)
{
XNamespace xmlns = sNs;
var results = from result in xd.Descendants(xmlns + sMethod + "Response")
let xElement = result.Element(xmlns + sMethod + "Result")
where xElement != null
select xElement.Value;
foreach (var item in results)
sr = item;
br = (sr.Equals("true"));
return sr;
}
return "Invalid XML " + Environment.NewLine + sXml;
}
catch (Exception ex)
{
return "Invalid XML " + Environment.NewLine + ex.Message + Environment.NewLine + sXml;
}
}
Maybe like this:
IEnumerable<XElement> list = doc.Document.Descendants("Result");
if (list.Count() > 0)
{
// do stuff
}
You're searching in the right direction, it definitely has to do with the namespace.
The code below returns the first element found for the combination of namespace and element name.
XDocument doc = XDocument.Load(#"c:\temp\file.xml");
XNamespace ns = #"http://mycrazyservice.com/SuperDuperService";
XElement el = doc.Elements().DescendantsAndSelf().FirstOrDefault( e => e.Name == ns + "Result");
You can try with this.
Regex regex = new Regex("<Result>(.*)</Result>");
var v = regex.Match(yourResponse);
string s = v.Groups[1].ToString();
Related
I'm doing some file clean up in an xml file and trying to use string.Replace to replace certain text blocks but it does not seem to be replacing the text that I am searching on.
My clean up code is follows
private Stream PrepareFile(string path)
{
string data = File.ReadAllText(path);
var newData = data.Replace("<a:FMax xmlns:b=\"http://www.w3.org/2001/XMLSchema\" i:type=\"b:string\"/>", "<a:FMax>0</a:FMax>")
.Replace("<a:KVy xmlns:b=\"http://www.w3.org/2001/XMLSchema\" i:type=\"b:string\"/>", "<a:KVy>0</a:KVy>")
.Replace("<a:Td xmlns:b=\"http://www.w3.org/2001/XMLSchema\" i:type=\"b:string\"/>", "<a:Td>0</a:Td>")
.Replace("<a:VyLim xmlns:b=\"http://www.w3.org/2001/XMLSchema\" i:type=\"b:string\"/>", "<a:VyLim>0</a:VyLim>");
var newData2 = newData.Replace("<a:VxTableSxI3_2I xmlns:b=\"http://www.w3.org/2001/XMLSchema\" i:type=\"b:string\"/>", "<a:VxTableSxI3_2I>0</a:VxTableSxI3_2I>");
byte[] bytes = Encoding.ASCII.GetBytes(newData2);
return new MemoryStream(bytes);
}
I should be able to write back to the original 'data' variable, but I split the variables out to be able to compare the strings before and after the replace. My xml file contains the following values(copied verbatim)
<a:LongitudinalTracker z:Id="i58">
<Name xmlns="http://schemas.datacontract.org/2004/07/HmsSim.EntityModule.BaseTypes" i:nil="true"/>
<a:FMax xmlns:b="http://www.w3.org/2001/XMLSchema" i:type="b:string"/>
<a:K>2</a:K>
<a:KVy xmlns:b="http://www.w3.org/2001/XMLSchema" i:type="b:string"/>
<a:Td xmlns:b="http://www.w3.org/2001/XMLSchema" i:type="b:string"/>
<a:VyLim xmlns:b="http://www.w3.org/2001/XMLSchema" i:type="b:string"/>
</a:LongitudinalTracker>
And the before and after strings look identical. I'm sure I am missing something silly, but I can't see what it is. Most of the answers to similar questions point out that the original code is not using the return value, but in this case I am definitely using the return value.
As suggested I am posting the code that ended up solving this.
private Stream PrepareFile(string path)
{
string data = File.ReadAllText(path);
var xml = XDocument.Parse(data);
XNamespace ns = "http://schemas.datacontract.org/2004/07/HmsSim.EntityModule.Entities.SimulationEntities.Track";
var longTracker = from item in xml.Descendants(ns + "LongitudinalTracker") select item;
foreach (var xElement in longTracker.Elements())
{
XNamespace nsI = "http://www.w3.org/2001/XMLSchema-instance";
if (xElement.Attribute(nsI + "type") != null)
{
xElement.Attribute(nsI + "type").Remove();
XAttribute attribute = new XAttribute(nsI + "nil", "true");
xElement.Add(attribute);
}
}
var latTracker = from item in xml.Descendants(ns + "LateralTracker") select item;
foreach (var xElement in latTracker.Elements())
{
XNamespace nsI = "http://www.w3.org/2001/XMLSchema-instance";
if (xElement.Attribute(nsI + "type") != null)
{
xElement.Attribute(nsI + "type").Remove();
XAttribute attribute = new XAttribute(nsI + "nil", "true");
xElement.Add(attribute);
}
}
Stream stream = new MemoryStream();
xml.Save(stream);
// Rewind the stream ready to read from it elsewhere
stream.Position = 0;
return stream;
}
This code works and is less brittle than the original code. As always, suggestions are welcome. Thanks to everyone who commented and led me towards this answer, I appreciate it.
I am not able to get the value from this xml response, I will appreciate any help.
<Response>
<Result>
<Item1>GREEN</Item1>
<Item2>05/19/2017 22:08:14</Item2>
</Result>
<Other>
<Id>xxxxxxxxxxxxc</Id>
</Other>
</Response>
What I tried so far but the results is empty
string responseXml = response.ToXML();
XElement doc = XElement.Load(new StringReader(responseXml));
var results = from p in
doc.Descendants("Result")
select new
{
item = p.Element("Item1").Value,
};
foreach (var elm in results)
{
Console.WriteLine(elm.item);
}
Use Parse instead of load. You may also be getting error due to extra characters in the string. In the string you postged there are single quotes. Not sure if the single quote is in the actual string you are using.
string responseXml = "<Response>" +
"<Result>" +
"<Item1>GREEN</Item1>" +
"<Item2>05/19/2017 22:08:14</Item2>" +
"</Result>" +
"<Other>" +
"<Id>xxxxxxxxxxxxc</Id>" +
"</Other>" +
"</Response>";
XElement doc = XElement.Parse(responseXml);
var results = from p in
doc.Descendants("Result")
select new
{
item = p.Element("Item1").Value,
};
foreach (var elm in results)
{
Console.WriteLine(elm.item);
}
I can't seem to get a value from child nodes of an xml file. I feel like I have tried everything. All I want is to get the value of latitude and longitude of the location child node in the xml file. What am I doing wrong? Maybe I should try JSON instead of XML.
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
StreamReader stream = new StreamReader(response.GetResponseStream());
try
{
XDocument xdoc = XDocument.Load(stream);
XElement root = xdoc.Root;
XNamespace ns = xdoc.Root.Name.Namespace;
List<XElement> results = xdoc.Descendants(ns + "GeocodeResponse").Descendants(ns + "result").ToList();
List<XElement> locationElement = results.Descendants(ns + "geometry").Descendants(ns + "location").ToList();
List<XElement> lat = locationElement.Descendants(ns + "lat").ToList();
List<XElement> lng = locationElement.Descendants(ns + "lng").ToList();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message)
}
}
xml
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>134 Gearger Circle, Lexington, KY, USA</formatted_address>
<geometry>
<location>
<lat>36.31228546</lat>
<lng>-91.4444399</lng>
</location>
<location_type>ROOFTOP</location_type>
</geometry>
<place_id>ChIJtwDV05mW-IgRyJKZ7fjmYVc</place_id>
</result>
</GeocodeResponse>
Also here is a debug value that shows a count of zero. not sure what that means. I just need the value of lat and lng.
If I understand your question correctly you are looking for the list of all the lat and lng in the XML Document.
XDocument xdc = XDocument.Load(stream);
var AllLats = xdc.Descendants("lat");
var AllLong = xdc.Descendants("lng");
You wont need to drill down to the hierarchy to get the XML Nodes value with Descendants
Another part is ns that is your namespace has to be included for the XML which looks like
<SOmeNS:address_component>
not for the elements which does have name without :
attaching the screenshot to see if you want this output.
Your code works correctly, make sure your xml loaded in the line using debugger.
XDocument xdoc = XDocument.Load(stream);
And check namespace, when executing your code i got empty string in ns or try removing the ns from your code.
XNamespace ns = xdoc.Root.Name.Namespace;
To get the lat and long use below code.
List<XElement> lat = locationElement.Descendants(ns + "lat").ToList();
List<XElement> lng = locationElement.Descendants(ns + "lng").ToList();
var latitudeval = lat[0].value;
var longitudeval = lng[0].value;
Get the element you are interested in by name. Then get the first and last child node since the first child is lat and the last child is long.
var sw = doc.Descendants("location");
var lat = sw.Descendants().First();
var lng = sw.Descendants().Last();
//XNamespace ns = xdoc.Root.Name.Namespace;
XNamespace ns = xdoc.GetDefaultNamespace();
The only way I was able to fix my issue was to send a request for JSON instead of XML. Then using Regex I was able to remove the <string> portion of the response. This worked perfectly and JSON is easier to work with in my opinion anyways.
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
JObject jdoc = null;
Stream stream = response.GetResponseStream();
try
{
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Regex rgx = new Regex("<.*\\>");
string newResult = rgx.Replace(text, "");
JObject json = JObject.Parse(newResult);
jdoc = json;
JArray results = (JArray)json["results"];
if (results.Count == 0)
{
}
else
{
foreach(JObject obj in results)
{
string formattedAddress = (string)obj["formatted_address"];
double lat = (double)obj["geometry"]["location"]["lat"];
double lng = (double)obj["geometry"]["location"]["lng"];
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
}
}
I'm having a heck of a time parsing this layout:
<string xmlns="http://www.namespaceuri.com/Admin/ws">
<CardTrxSummary>
<PaymentMethod>
<Payment_Type_ID>VISA </Payment_Type_ID>
<Authorization>0.0000</Authorization>
<Capture>0.0000</Capture> <ForceCapture>0.0000</ForceCapture>
<PostAuth>0.0000</PostAuth> <Return>0.0000</Return>
<Sale>3419.2700</Sale> <Receipt>0.0000</Receipt>
<RepeatSale>0.0000</RepeatSale>
<Activate>0.0000</Activate>
<Deactivate>0.0000</Deactivate>
<Reload>0.0000</Reload>
<Authorization_Cnt>0</Authorization_Cnt>
<Capture_Cnt>0</Capture_Cnt>
<ForceCapture_Cnt>0</ForceCapture_Cnt>
<PostAuth_Cnt>0</PostAuth_Cnt>
<Return_Cnt>0</Return_Cnt>
<Sale_Cnt>13</Sale_Cnt>
<Receipt_Cnt>0</Receipt_Cnt>
<RepeatSale_Cnt>0</RepeatSale_Cnt>
<Activate_Cnt>0</Activate_Cnt>
<Deactivate_Cnt>0</Deactivate_Cnt>
<Reload_Cnt>0</Reload_Cnt>
<Cnt>13</Cnt>
</PaymentMethod>
</CardTrxSummary>
</string>
I am trying with this code to get the a specific result:
private static string ReadValueFromXml(XmlDocument xmlDocument, string field)
{
var xdoc = xmlDocument.ToXDocument();
var ns = "http://www.namespaceuri.com/Admin/ws";
return xdoc.Descendants(ns + "PaymentMethod")
.Select(x => (string) x.Attribute("Cnt"))
.FirstOrDefault();
}
At this point, it's giving me this message:
The ':' character, hexadecimal value 0x3A, cannot be included in a
name.
I tried it this way:
XmlNodeList xnList = xmlDocument.SelectNodes("/CardTrxSummary/PaymentMethod");
foreach (XmlNode xn in xnList)
{
Console.WriteLine("Sale: " + xn["Sale"].InnerText);
Console.WriteLine("Sale_Cnt: " + xn["Sale_Cnt"].InnerText);
Console.WriteLine("Payment_Type_ID: " + xn["Payment_Type_ID"].InnerText);
}
And it never went inside the foreach.
How do I get the values within PaymentMethod?
EDIT
I looked at the xmldocument's innertext and this is how it's displayed:
"<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://www.namespaceuri.com/Admin/ws\"><CardTrxSummary>\r\n <PaymentMethod>\r\n <Payment_Type_ID>VISA </Payment_Type_ID>\r\n <Authorization>0.0000</Authorization>\r\n <Capture>0.0000</Capture>\r\n <ForceCapture>0.0000</ForceCapture>\r\n <PostAuth>0.0000</PostAuth>\r\n <Return>0.0000</Return>\r\n <Sale>3419.2700</Sale>\r\n <Receipt>0.0000</Receipt>\r\n <RepeatSale>0.0000</RepeatSale>\r\n <Activate>0.0000</Activate>\r\n <Deactivate>0.0000</Deactivate>\r\n <Reload>0.0000</Reload>\r\n <Authorization_Cnt>0</Authorization_Cnt>\r\n <Capture_Cnt>0</Capture_Cnt>\r\n <ForceCapture_Cnt>0</ForceCapture_Cnt>\r\n <PostAuth_Cnt>0</PostAuth_Cnt>\r\n <Return_Cnt>0</Return_Cnt>\r\n <Sale_Cnt>13</Sale_Cnt>\r\n <Receipt_Cnt>0</Receipt_Cnt>\r\n <RepeatSale_Cnt>0</RepeatSale_Cnt>\r\n <Activate_Cnt>0</Activate_Cnt>\r\n <Deactivate_Cnt>0</Deactivate_Cnt>\r\n <Reload_Cnt>0</Reload_Cnt>\r\n <Cnt>13</Cnt>\r\n </PaymentMethod>\r\n</CardTrxSummary></string>"
Which, I assume, is part of my problem?
EDIT#2
This is what I ended up doing to get it to work. I'm sure there is a better way:
var tst2 = tst.InnerText.Replace("<", "<").Replace(">", ">").Replace("\r\n", string.Empty);
Console.WriteLine("Cnt: " + ReadXmlValue1(tst2, "Cnt"));
and my method to parse it:
private static void ReadXmlValue1(string xmlDocument)
{
XDocument xdoc = XDocument.Parse(xmlDocument);
//XNamespace ns = "http://www.namespaceuri.com/Admin/ws";
var payments = from p in xdoc.Descendants("PaymentMethod")
select new
{
Sale = (decimal)p.Element("Sale"),
SaleCount = (int)p.Element("Sale_Cnt"),
PaymentType = (string)p.Element("Payment_Type_ID")
};
Console.WriteLine("Count: " + payments.Count());
foreach (var payment in payments)
{
Console.WriteLine("Sale: " + payment.Sale);
Console.WriteLine("Sale_Cnt: " + payment.SaleCount);
Console.WriteLine("Payment_Type_ID: " + payment.PaymentType);
}
}
EDIT#3
This is how I'm creating the xmldocument:
/// <summary>
/// Get Data in xml format by url
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static XmlDocument GetXmlDataFromUrl(string url)
{
//requesting the particular web page
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
//geting the response from the request url
var response = (HttpWebResponse)httpRequest.GetResponse();
//create a stream to hold the contents of the response (in this case it is the contents of the XML file
var receiveStream = response.GetResponseStream();
//creating XML document
var mySourceDoc = new XmlDocument();
//load the file from the stream
if (receiveStream != null)
{
mySourceDoc.Load(receiveStream);
//close the stream
receiveStream.Close();
return mySourceDoc;
}
return null;
}
You can use LINQ to XML to get list of strongly typed anonymous payment objects:
WebClient client = new WebClient();
string content = client.DownloadString(url);
XDocument xdoc = XDocument.Parse(content);
XNamespace ns = "http://www.namespaceuri.com/Admin/ws";
var payments = from p in xdoc.Descendants(ns + "PaymentMethod")
select new {
Sale = (decimal)p.Element(ns + "Sale"),
SaleCount = (int)p.Element(ns + "Sale_Cnt"),
PaymentType = (string)p.Element(ns + "Payment_Type_ID")
};
Keep in mind, that your xml has namespace declared, so you should provide it when specifying element names.
Usage:
foreach(var payment in payments)
{
Console.WriteLine("Sale: " + payment.Sale);
Console.WriteLine("Sale_Cnt: " + payment.SaleCount);
Console.WriteLine("Payment_Type_ID: " + payment.PaymentType);
}
XmlNode node = xmlDocument.SelectSingleNode("/string/CardTrxSummary/PaymentMethod");
Console.WriteLine("Sale: " + node.SelectSingleNode("Sale").InnerText);
Console.WriteLine("Sale_Cnt: " + node.SelectSingleNode("Sale_Cnt").InnerText);
Console.WriteLine("Payment_Type_ID: " + node.SelectSingleNode("Payment_Type_ID").InnerText);
or you can use getElementByTagName instead;
Console.WriteLine("Sale: " + xmlDocument.getElementByTagName("Sale").InnerText);
Console.WriteLine("Sale_Cnt: " + xmlDocument.getElementByTagName("Sale_Cnt").InnerText);
Console.WriteLine("Payment_Type_ID: " + xmlDocument.getElementByTagName("Payment_Type_ID").InnerText);
And just a note, the above 2 method is assuming that the tag will never return null.
If you want to handle possible null node, you can do something like this.
string text = xmlDocument.getElementByTagName("Sale") != null ? xmlDocument.getElementByTagName("Sale").InnerText : "unidentified";
The above line has the format like this:
var variable = condition ? A : B;
It's basically saying that if condition is true, variable equals A, otherwise variable equals B.
I have this LINQ query:
XNamespace ns = NAMESPACE;
var items = (from c in doc.Descendants(ns +"Item")
select new Item
{
Title = c.Element(ns + "ItemAttributes").Element(ns + "Title").Value,
MFR = c.Element(ns + "ItemAttributes").Element(ns + "Manufacturer").Value,
Offer = c.Element(ns + "Offers").Element(ns + "TotalOffers").Value,
Amazon = c.Element(ns + "Offer").Element(ns + "Merchant").Elements(ns + "MerchantId"),
LowPrice = Convert.ToDouble(c.Element(ns + "FormattedPrice").Value),
SalesRank = Convert.ToInt32(c.Element(ns +"SalesRank").Value),
ASIN = c.Element(ns + "ASIN").Value
}).ToList<Item>();
It works great expect for when a node is not present. For example it my not have a MFR or a sales rank. How can I make it so if it does not have the node in question, it gives me a default value or at the very doesn't make me try catch my whole query for one item.
As far as I'm aware LINQ to XML doesn't support this. However I ran into this same mess in a project I was working on and created this extension for XElement to allow it. Maybe it could work for you:
public static XElement ElementOrDummy(this XElement parentElement,
XName name,
bool ignoreCase)
{
XElement existingElement = null;
if (ignoreCase)
{
string sName = name.LocalName.ToLower();
foreach (var child in parentElement.Elements())
{
if (child.Name.LocalName.ToLower() == sName)
{
existingElement = child;
break;
}
}
}
else
existingElement = parentElement.Element(name);
if (existingElement == null)
existingElement = new XElement(name, string.Empty);
return existingElement;
}
Basically it just checks to see if the element exists and if it doesn't it returns one with the same name and an empty value.
You can use XElement Explicit Conversion, e.g.:
(int?)c.Element(ns +"SalesRank")
Reference: http://msdn.microsoft.com/en-us/library/bb340386.aspx
if the problem that the XElement exists, but the value is blank? i.e.
<Item>
<ItemAttributes>
<Manufacturer></Manufacturer>
</ItemAttributes>
</Item>
then you can use the string.IsNullOrEmpty function
XNamespace ns = NAMESPACE;
var items = (from c in doc.Descendants(ns +"Item")
select new Item
{
MFR = if (string.IsNullOrEmpty(c.Element(ns + "ItemAttributes").Element(ns + "Manufacturer").Value)) ? "default value here" : c.Element(ns + "ItemAttributes").Element(ns + "Manufacturer").Value,
// omitted for brevity
}).ToList<Item>();