Navigate xml nodes; - c#

Hi I have an xml data returned from another service. It looks like this
<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://test.com/group/application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Response>
<Response>
<ReturnCode>0</ReturnCode>
<Message>Sucess</Message>
<Data>PRINT 'This is a test #2'</Data>
</Response>
</Response>
</response>
I need the value of Data, Message and ReturnCode. The value inside the Data(PRINT 'This is a test #2') node could be single line or thousands of lines..
I am using this C# code to get the values
XmlDocument xm = new XmlDocument();
string Response = obj.getContent(str, 1, 73810, SHA);
//Console.WriteLine("Response" + Response);
xm.LoadXml(Response);
Console.WriteLine(xm.InnerXml);
XmlNode oldCd;
XmlElement root = xm.DocumentElement;
Console.WriteLine(root.InnerText);
oldCd = root.SelectSingleNode("/response/Response/Response/ReturnCode/Message/Data/");
static void Main()
{
try
{
svc obj = new svc();
..
//XmlDocument xm = new XmlDocument();
string rsp = obj.getContent(..;
String myEncodedString;
myEncodedString = obj.XmlDecode(rsp);
XNamespace xmlns = XNamespace.Get("http://xxxx.com/xxx/xx");
XDocument doc = XDocument.Parse(myEncodedString);
Console.WriteLine(obj.Return_Message_Data("ReturnCode", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Message", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Data", myEncodedString));
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}

Try this
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/responset[#*]/Response");
foreach (XmlNode xn in xnList)
{
XmlNode response = xn.SelectSingleNode("Response");
if (response != null)
{
string rc = response["ReturnCode"].InnerText;
string msg = example["Message"].InnerText;
string data = example["Data"].InnerText;
}
}

Related

read xml file on c#, reading the arabic text provide a encrypted string not actual utf-8

xml file-> for example this is hosted on the url http://localhost/test1
<?xml version="1.0" encoding="utf-8"?>
<MSG>
<arabic>
<translationOne>اول</translationOne>
<translationTwo>دوم</translationTwo>
</arabic>
<persian>
<translationOne>یک</translationOne>
<translationTwo>دوم</translationTwo>
</persian>
</MSG>
c# class
var m_strFilePath = "http://localhost/test1";
string xmlStr;
using (var wc = new WebClient())
{
xmlStr = wc.DownloadString(m_strFilePath);
}
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlStr);
XmlNodeList unNodeA = xmldoc.SelectNodes("MSG/arabic");
XmlNodeList unNodeP = xmldoc.SelectNodes("MSG/persian");
string arabic = "";
foreach (XmlNode i in unNodeA)
{
arabic += i["translationOne"].InnerText;
}
string persian= "";
string persian2 ="";
foreach (XmlNode ii in unNodeP)
{
persian+= ii["translationOne"].InnerText;
persian2+= ii["translationTwo"].InnerText;
}
->>print(arabic and persian);
here the test contain not correct format like (اول دوم) it's some kind of (عبد العزيز عباسین)
It is better to use LINQ to XML API. It is available in the .Net Framework since 2007.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<?xml version='1.0' encoding='utf-8'?><MSG>
<arabic>
<translationOne>اول</translationOne>
<translationTwo>دوم</translationTwo>
</arabic>
<persian>
<translationOne>یک</translationOne>
<translationTwo>دوم</translationTwo>
</persian>
</MSG>");
foreach (XElement elem in xdoc.Descendants("arabic").Elements())
{
Console.WriteLine("translation: {0}", elem.Value);
}
}
If you need to load XML from the URL:
const string Url = #"http://hurt.super-toys.pl/xml/super_toys_ceneo_pelny.xml";
XDocument xdoc = XDocument.Load(Url);
Output
translation: اول
translation: دوم

XDocument just reads the first title?

I need to parse xml but my code just parses one title not all.
How can I parse part ?
This is my code:
CustomResponse itemCustom = new CustomResponse ();
XDocument response = XDocument.Parse(responseXml);
XElement rootElement = response.Root;
foreach (XElement sellResponse in rootElement.Elements())
{
itemCustom .ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom .ErrorMessage = sellResponse.Element("ErrorMessage").Value;
itemCustom .CustomerID= sellResponse.Element("CustomerID").Value;
itemCustom .CustomerType= sellResponse.Element("CustomerType").Value;
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<TINS_XML_DATA>
<Header>
<ErrorCode>WAATS</ErrorCode>
<ErrorMessage>UTL</ErrorMessage>
</Header>
<Customer>
<CustomerID>UTL11111111111111111111</CustomerID>
<CustomerType>NSell</CustomerType>
</Customer>
</TINS_XML_DATA>
Try something like this:
foreach (XElement sellResponse in rootElement.Elements())
{
if (sellResponse.Name == "Header")
{
itemCustom.ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom.ErrorMessage = sellResponse.Element("ErrorMessage").Value;
}
else if (sellResponse.Name == "Customer")
{
itemCustom.CustomerID = sellResponse.Element("CustomerID").Value;
itemCustom.CustomerType = sellResponse.Element("CustomerType").Value;
}
}
Update: You could also use XPath to find required elements as like below:
var xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var errorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
This is my solved:
var xDoc = new XmlDocument();
xDoc.LoadXml(responseXml);
itemSell.ErrorCode = xDoc.SelectNodes("//ErrorCode")[0].InnerText;
itemSell.ErrorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
itemSell.CustomerID= xDoc.SelectNodes("//CustomerID")[0].InnerText;

Query for unique id with XDocument

I have the following XML name Sample.xml which I am trying to query uniqueID with XDocument:
<Request>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="3221">
<AccountNo>83838</AccountNo>
<FirstName>Tom</FirstName>
<LastName>Jackson</LastName>
</Person>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="21132">
<AccountNo>789875</AccountNo>
<FirstName>Chris</FirstName>
<LastName>Smith</LastName>
</Person>
</Request>
How do i write code to extract uniqueID of all persons.
You can use LINQ to XML to retrieve the unique ID from your XML document.
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XDocument doc = XDocument.Parse(xml);
XNamespace ns = "http://CompanyName.AppName.version1";
var uniqueIDs = doc.Descendants(ns + "Person")
.Select(p => p.Attribute("uniqueID").Value)
.ToList();
Try below code With XmlDocument in place
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Person");
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.Attributes["uniqueID"].Value);
}
You can get the Unique ID by:
string xml="Your XML String";
XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xml));
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
string uniqueID = chldNode.Attributes["uniqueID"].Value;
Response.Write(employeeName + "<br />");
}
}
}

Edit XML Document from WebService Method

I've got a Web Service that uses an XML document and I'm trying to add a function that adds a new node to the XML document. It runs fine and doesn't break, but the save function doesn't seem to work? Here's the code;
[WebMethod]
public void AddNodeTEST()
{
XmlDocument xmlUpdateCfg = new XmlDocument();
try
{
xmlUpdateCfg.Load(Context.Request.MapPath("Updates.xml"));
}
catch (Exception ex)
{
}
XmlNode updateInfo = xmlUpdateCfg.SelectSingleNode("updateinfo");
/* Create the downloadmodule node */
XmlNode newDownloadModule = xmlUpdateCfg.CreateNode(XmlNodeType.Element, "downloadmodule", null);
newDownloadModule.InnerText = "download/test.CAB";
XmlAttribute downloadModuleName = xmlUpdateCfg.CreateAttribute("name");
downloadModuleName.Value = "Test";
newDownloadModule.Attributes.Append(downloadModuleName);
/* Create the version node */
XmlNode newVersion = xmlUpdateCfg.CreateNode(XmlNodeType.Element, "version", null);
XmlAttribute versionMaj = xmlUpdateCfg.CreateAttribute("maj");
versionMaj.Value = "1";
XmlAttribute versionMin = xmlUpdateCfg.CreateAttribute("min");
versionMin.Value = "2";
XmlAttribute versionBld = xmlUpdateCfg.CreateAttribute("bld");
versionBld.Value = "3";
XmlAttribute versionRev = xmlUpdateCfg.CreateAttribute("rev");
versionRev.Value = "4";
newVersion.Attributes.Append(versionMaj);
newVersion.Attributes.Append(versionMin);
newVersion.Attributes.Append(versionBld);
newVersion.Attributes.Append(versionRev);
/* Add the newVersion node to the newDownloadModule node */
newDownloadModule.AppendChild(newVersion);
/* Add the newDownloadModule to the updateinfo Node*/
updateInfo.AppendChild(newDownloadModule);
xmlUpdateCfg.Save("Updates.xml");
}
and here is the XML structure;
<?xml version="1.0" encoding="utf-8" ?>
<updateinfo>
<downloadmodule name="test">
<version maj="1" min="0" bld="4" rev="0"/>
Download/cabfile.CAB
</downloadmodule>
</updateinfo>
Any help is appreciated, thanks!.
Shouldn't you be calling xmlUpdateCfg.Save(Context.Request.MapPath("Updates.xml")) so that it saves it to the same location it read it from?

Reading SOAP xml answer

I have to read a SOAP answer from the file below
<?xml version="1.0"?>
<Envelopes>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Body>
<env:Fault>
<env:Code>
<env:Value>env:Receiver</env:Value>
<env:Subcode>
<env:Value>-1</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en">CServiceData::SetPropertyValue failed; '</env:Text>
</env:Reason>
<env:Detail>
<Object>4</Object>
<ObjectIndex>1</ObjectIndex>
<Command>AddObject</Command>
<SessionID>B8FE2330-4252-4BB1-A3EE-053F4413A0C0</SessionID>
</env:Detail>
</env:Fault>
</env:Body>
</env:Envelope>
</Envelopes>
I only need the content of the Text tag CServiceData::SetPropertyValue failed;
You can use XPath:
public string GetErrorMessage(string xml)
{
using (StringReader sr = new StringReader(xml))
{
var doc = new XPathDocument(sr);
var nav = doc.CreateNavigator();
var xmlNs = new XmlNamespaceManager(nav.NameTable);
xmlNs.AddNamespace("env", #"http://www.w3.org/2003/05/soap-envelope");
var node = nav.SelectSingleNode("//env:Text", xmlNs);
return node.Value;
}
}
or you can use LINQ To XML:
public string GetErrorMessage(string xml)
{
var doc = XDocument.Parse(xml);
var node = doc.Descendants(XName.Get("Text", #"http://www.w3.org/2003/05/soap-envelope"))
.FirstOrDefault();
return node.Value;
}

Categories

Resources