Unable to Parse XMl after unwrapping soap body - c#

I have been trying hard to parse an xml string, but all to no avail
<EnquirySingleItemResponse xmlns="http://tempuri.org/"> <EnquirySingleItemResult>
<Response>
<MSG>SUCCESS</MSG>
<INFO>TESTING</INFO>
</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>
My Code returns null or the texts in the xml tags no matter how i parse it. I have checked some post, but they seem not to be working.
See my code snipped below
XElement anotherUnwrappedResponse = ( from _xml in axdoc.Descendants(tempuri + "EnquirySingleItemResponse")
select _xml).FirstOrDefault();
string response = anotherUnwrappedResponse.Value;
axdoc.Descendants is used because i unwrapped the soap body, to have the xml above

Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<EnquirySingleItemResponse xmlns=\"http://tempuri.org/\">" +
"<EnquirySingleItemResult>" +
"<Response>" +
"<MSG>SUCCESS</MSG>" +
"<INFO>TESTING</INFO>" +
"</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>";
XDocument doc = XDocument.Parse(input);
string msg = doc.Descendants().Where(x => x.Name.LocalName == "MSG").FirstOrDefault().Value;
string info = doc.Descendants().Where(x => x.Name.LocalName == "INFO").FirstOrDefault().Value;
}
}
}
​

Related

How to replace Xml Attribute Prefix value by using C#

<ce_table frame="topbot" id="t0010" rowsep="0" colsep="0">
<ce_label>Table 2</ce_label>
<ce_caption id="cn040">
<ce_simple-para id="spar055">Model fit cnbs for the span targeted moments.</ce_simple-para>
</ce_caption>
</ce_label>
</ce_table>
I need to change id="t0010" to id="tf0010" and id="cn.. " to id="cib.. ".
I only need to change prefix of an attribute value.
Use xml linq :
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement ce_table = doc.Descendants("ce_table").First();
ce_table.SetAttributeValue("id", "tf0010");
XElement ce_caption = ce_table.Descendants("ce_caption").First();
ce_caption.SetAttributeValue("id", "cib040");
}
}
}

Update multiple XML nodes that match an Xpath query C#

I am trying to update the content of multiple nodes that match a specific xpath. For example, in the below example, I want to update any attribute1 node that currently is '2' with 'Hello'. What is the best way to do this?
(DotNetFiddle Here)
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
}
This may could help you :
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
// getting the list of nodes with XPath query :
XmlNodeList nodes = job.SelectNodes("//attribute1[text()=2]");
foreach (XmlNode child in nodes)
{
// replacing the old value with the new value
child.InnerText = newAttribute1Value ;
}
}

XML C# Parse - Complex

I have been on google for a while but am just stumped. I need to parse xml of this nature. I can't seem to skip to elements in the middle, e.g. Folder. I have limited the xml as there were many 'Folder' elements. Any guidance would be appreciated. I was after the FolderID element's attribute ID.
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ServerVersionInfo MajorVersion="14"
MinorVersion="1"
MajorBuildNumber="225"
MinorBuildNumber="46"
Version="Exchange2010_SP1"
xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:GetFolderResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Folders>
<t:Folder>
<t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
<t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
<t:DisplayName>Top of Information Store</t:DisplayName>
<t:TotalCount>0</t:TotalCount>
<t:ChildFolderCount>15</t:ChildFolderCount>
<t:EffectiveRights>
<t:CreateAssociated>true</t:CreateAssociated>
<t:CreateContents>true</t:CreateContents>
<t:CreateHierarchy>true</t:CreateHierarchy>
<t:Delete>true</t:Delete>
<t:Modify>true</t:Modify>
<t:Read>true</t:Read>
<t:ViewPrivateItems>true</t:ViewPrivateItems>
</t:EffectiveRights>
<t:PermissionSet>
<t:Permissions>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Default</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Anonymous</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
</t:Permissions>
</t:PermissionSet>
<t:UnreadCount>0</t:UnreadCount>
</t:Folder>
</m:Folders>
</m:GetFolderResponseMessage>
</m:ResponseMessages>
</m:GetFolderResponse>
</s:Body>
</s:Envelope>
LINQ to XML is the best .NET XML Parsing API.
See
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load(#"c:\temp\foo.xml");
var ns = (XNamespace)"http://schemas.microsoft.com/exchange/services/2006/types";
var folders = doc.Descendants(ns + "Folder");
foreach (var e in folders)
{
var folderId = e.Element(ns + "FolderId").Attribute("Id").Value;
Console.WriteLine(folderId);
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
}
You should learn about serlialization. It's very easy to convert an XML to and from a object in C#. https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part
That said, this will get you the data you're after. It's not very reusable and won't help you with any xml files other than ones with one instance of that attribute, but it's what you're after so here you go.
string FolderId;
string ChangeKey;
using (StreamReader sr = new StreamReader("c:\\myfile.xml"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("<t:FolderId Id="))
{
try
{
var lineArray = line.Split('\"');
FolderId = lineArray[1];
ChangeKey = lineArray[3];
}
catch
{
// handle exception
}
}
}
}
You can use the XSD.exe to create a schema class. and then using XML deserializer, you can deserialize/parse xml to object
Using xml linq
XDocument doc = XDocument.Load(FILENAME);
List<XElement> folders = doc.Descendants().Where(x => x.Name.LocalName == "Folder").ToList();
XNamespace tNs = folders.FirstOrDefault().GetNamespaceOfPrefix("t");
XElement id_AAMkADk5MmY1ZThmLTM2MzAtNGVh = folders.Where(x => (string)x.Element(tNs + "FolderId").Attribute("Id") == "AAMkADk5MmY1ZThmLTM2MzAtNGVh").FirstOrDefault();

XML and JSP parsing in C#

I have this XML feed file and I don`t know how to handle a problem.
So, the code is:
<PRICE>
<WIC>GA-H110M-S2H</WIC>
<DESCRIPTION>
GIGABYTE Main Board Desktop INTEL H110 (Socket LGA1151,2xDDR4,VGA/HDMI/DVI,1xPCIEX16/2xPCIEX1,USB3.0/USB2.0, 6xSATA III,LAN) micro ATX retail
</DESCRIPTION>
<VENDOR_NAME>GIGABYTE</VENDOR_NAME>
<GROUP_NAME>Main Board Desktop</GROUP_NAME>
<VPF_NAME/>
<CURRENCY_CODE>USD</CURRENCY_CODE>
<AVAIL>0</AVAIL>
<RETAIL_PRICE>56.40</RETAIL_PRICE>
<MY_PRICE>52.71</MY_PRICE>
<WARRANTYTERM>36</WARRANTYTERM>
<GROUP_ID>32</GROUP_ID>
<VENDOR_ID>170192</VENDOR_ID>
<SMALL_IMAGE>
https://www.it4profit.com/catalogimg/wic/1/GA-H110M-S2H
</SMALL_IMAGE>
<PRODUCT_CARD>
https://content.it4profit.com/itshop/itemcard_cs.jsp?ITEM=151118121920215716&THEME=asbis&LANG=ro
</PRODUCT_CARD>
<EAN>4719331837310</EAN>
</PRICE>
Now, in PRODUCT_CARD are technical information for that product and I don`t know how to extract all data and then export to .csv using C# for example.
I haven't tried , but I am suggesting can do , this
Credits: Pulling data from a webpage, parsing it for specific pieces, and displaying it
string Url = "https://content.it4profit.com/itshop/itemcard_cs.jsp?ITEM=151118121920215716&THEME=asbis&LANG=ro";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
Real simple to get into dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("PRICE").Elements()
.GroupBy(x => x.Name.LocalName, y => (string)y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}

C# XmlDocument for grabbing API specific data?

I am trying to grab the specific value of an attribute in:
http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com
<SD>
<POPULARITY URL="bing.com/" TEXT="16" SOURCE="panel"/>
<REACH RANK="16"/>
<RANK DELTA="-7"/>
<COUNTRY CODE="US" NAME="United States" RANK="9"/>
</SD>
</ALEXA>
I want to grab the value of
I have the current Console Code for this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(url);
XmlNode root = xmldoc.SelectSingleNode("//#RANK");
//XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable);
//XmlNodeList nList1 = xmldoc.SelectNodes("//#RANK", xnm1);
Console.WriteLine(root.ToString());
Console.ReadLine();
}
}
}
But when I run it, I receive the following message in return:
System.Xml.XmlAttribute
What am I doing wrong?
Try changing:
Console.WriteLine(root.ToString());
to:
Console.WriteLine(root.Value);
Hope that helps.

Categories