Parse ASMX XML web service result - c#

I'm getting this XML structure from an ASMX web service.
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfSecurityUser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://sales.newsite.com/">
<SecurityUser>
<id>AAA1D75</id>
<code />
<lastName>Thumb</lastName>
<firstName>Tom</firstName>
<middleInitial />
</SecurityUser>
</ArrayOfSecurityUser>
How do I parse it to get the full name using C# ASP.NET?
I have tried the following:
XDocument x = XDocument.Load("GetUserInfo.xml");
XNamespace ns = "http://sales.newsite.com/";
but I don't know how to parse it.

After that point all you have to do is read the elements and format the string such as:
string fullname = string.Format("{0} {1} {2}",
x.Descendants(ns + "firstName").First().Value,
x.Descendants(ns + "middleInitial").First().Value,
x.Descendants(ns + "lastName").First().Value);
This is assuming there is only one SecurityUser. If there are multiple entries, instead you have to loop through instead of getting the first one.

Related

How do I generate this XML in C#? [duplicate]

This question already has answers here:
Add Stylesheet reference to XML Document in Linq?
(1 answer)
Creating XDocument with xsi:schemaLocation namespace
(1 answer)
Closed last year.
I have an example XML file that I need to generate on the fly in a console application.
This is an example of the first part of the required XML document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?>
<CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Envelope>
<EnvelopeNode NumOrdre="1">
</EnvelopeNode>
</Envelope>
</CPPData>
I have a method creates and returns an XElement which contains all the data required by the body of the XML (e.g. everything inside the CPPData element).
However I can't figure out how to add the following:
<?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?> to the XDocument
<CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> to the XElement
var xml = new XDocument();
var xp = new XProcessingInstruction(target: "xml-stylesheet", data: #"type=""text/xsl"" href=""ABC123.xsl""");
xml.Add(xp);
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
xml.Add(new XElement("root",
new XAttribute(ns + "noNamespaceSchemaLocation", "CPPData_V1.14.xsd"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
));

How to get enclosure url with XElement C# Console

I read multiple feed from many sources with C# Console, and i have this code where i load XML From sources:
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
XElement xdoc = XElement.Load(sourceURLX);
How to get enclosure url and show as variable?
If I understand your question correctly (I'm making a big assumption here) - you want to select an attribute from the root (or 'enclosing') tag, named 'url'?
You can make use of XPath queries here. Consider the following XML:
<?xml version="1.0" encoding="utf-8"?>
<root url='google.com'>
<inner />
</root>
You could use the following code to retrieve 'google.com':
String query = "/root[1]/#url";
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
String value = doc.SelectSingleNode(query).InnerText;
Further information about XPath syntax can be found here.
Edit: As you stated in your comment, you are working with the following XML:
<item>
<description>
</description>
<enclosure url="blablabla.com/img.jpg" />
</item>
Therefore, you can retrieve the url using the following XPath query:
/item[1]/enclosure[1]/#url
With xml like below
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>title</title>
<link>https://www.link.com</link>
<description>description</description>
<item>
<title>RSS</title>
<link>https://www.link.com/xml/xml_rss.asp</link>
<description>description</description>
<enclosure url="https://www.link.com/media/test.wmv"
length="10000"
type="video/wmv"/>
</item>
</channel>
</rss>
You will get url by reading attribute
var document = XDocument.Load(sourceURLX);
var url = document.Root
.Element("channel")
.Element("item")
.Element("enclosure")
.Attribute("url")
.Value;
To get multiple urls
var urls = document.Descendants("item")
.Select(item => item.Element("enclosure").Attribute("url").Value)
.ToList();
Using foreach loop
foreach (var item in document.Descendants("item"))
{
var title = item.Element("title").Value;
var link = item.Element("link").Value;
var description = item.Element("description").Value;
var url = item.Element("enclosure").Attribute("url").Value;
// save values to database
}

Remove specefic tag from xml

I have a webservice and it's response is:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">
<contractor-management>
<request-attributes> <corp-id>abcd</corp-id></request-attributes>
</contractor-management>
</string>
I am getting the above response but I want to remove the string tag line. So it should be like this:
<?xml version="1.0" encoding="utf-8" ?>
<contractor-management>
<request-attributes> <corp-id>abcd</corp-id></request-attributes>
</contractor-management>
Due to some reason("-" cannot be used as a part of variable name), I am creating the above like this:
string x;
x = "<contractor-management>";
x += "<request-attributes> ";
x += "<corp-id>abcd</corp-id> ";
x += "</request-attributes> ";
x = "</contractor-management>";
Do like below code, where xmlContent is your current xml contents
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlContent);
XmlNode firstChild=xmldoc.GetElementsByTagName("string")[0];
XmlNode secondChild = firstChild.FirstChild;
xmldoc.ReplaceChild(secondChild, firstChild);
You can also save this modified xml to a file
xmldoc.Save(#"modified.xml");

Var with XML after Digest Authentication

After a Digest authentication:
var resultText = Digester.GrabResponse("/blabla");
I have this in the var resulText:
<?xml version="1.0" encoding="utf-8"?>
<response>
<HELLO>
<time>08:10</time>
<date>11.08.09</date>
<temp>35.5</temp>
<humi>37.7</humi>
</HELLO>
</response>
I tried to fetch the value of the date with XDocument but it didn't work.
This is really simple: -
XDocument xml = XDocument.Parse(resultText.ToString());
var date = (from n in xml.Descendants("HELLO")
select n.Element("date").Value).SingleOrDefault().ToString();
You need to use the XDocument.Parse method. Looks like you're passing an XML string as a URI to the Load method which obviously wont work.

Regarding C# Xml Reading

I'm currently doing a XML file that includes the "name" of the city, the "region", "lat" latitude and "lng".
Here is my Code:
XmlDocument XmlFile = new XmlDocument();
try {
XmlFile.Load("..\\..\\liste.xml");
}
catch (Exception ex)
{
Console.WriteLine("Erreur" + ex.Message);
};
XmlNodeList MyNodeXML = XmlFile.GetElementsByTagName("city");
foreach (XmlNode unNode in MyNodeXML)
{
string nomVille = unNode.Attributes[0].Value;
string lat = unNode.Attributes[1].Value;
string lng = unNode.Attributes[2].Value;
listeCooVilles.Add(nomVille, new PointF(float.Parse(lat), float.Parse(lng)));
}
Where listeCooVilles is a Dictionnary.
Here is my XML: I did a sample for test:
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<city>
<name>Abercorn</name>
<region>Montérégie</region>
<lat>45.032999</lat>
<lng>-72.663057</lng>
</city>
<cities>
I saw many post doing the same as above in StackOverflow, but I still get an IndexOutOfRange Exception on the line
string nomVille = unNode.Attributes[0].Value;
Can someone help? Thanks!
The element has no attributes - only sub-elements. Attributes are name=value pairs at the same level as the element. E.g.
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<city name="Abercorn" region="Montérégie" lat="45.032999" lng="-72.663057" />
<city name="Granby" region="Montérégie" lat="45.4" lng="-72.733333" />
</cites>
Nesting elements (as you have done originally) and using attributes (as you've coded for) are both equally valid ways of structuring your XML document.
As pointed our those are elements not attributes. Your code needs to change to this:
nomVille = unNode.Item["name"].Value
region = unNode.Item["region"].Value
lat = unNode.Item["lat"].Value
lng = unNode.Item["lng"].Value
None of the nodes in your XML sample have attributes, which is why the collection has null elements in it.
Try changing it to:
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<city testAttr = "hello!">
<name>Abercorn</name>
<region>Montérégie</region>
<lat>45.032999</lat>
<lng>-72.663057</lng>
</city>
<cities>
The addition of the testAttr should provide a valid collection in unNode.Attributes.
You are using attributes in city tag but I think you should be using xml elements.

Categories

Resources