remove soap envelope header and get the XML - c#

I have a soap response, I want to remove all soap related things and get the inner XML with only one header.
response:
"<s:Envelope xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Body>
<getResponse xmlns = ""http://tempuri.org/"">
<getResult xmlns:xsi = ""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema"">
<Id>999</Id>
<EResponse>
<au>
<st>ABC</st>
<co>DGH</co>
<mo>MMM</mo>
</au>
</EResponse>
</getResult>
</getResponse>
</s:Body>
</s:Envelope>
I want to extract this:
<getResult xmlns:xsi = ""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema"">
<Id>999</Id>
<EResponse>
<au>
<st>ABC</st>
<co>DGH</co>
<mo>MMM</mo>
</au>
</EResponse>
</getResult>
I am trying this:
XDocument input;
using (var nodeReader = new XmlNodeReader(doc))
{
nodeReader.MoveToContent();
input = XDocument.Load(nodeReader);
}
var xns = XNamespace.Get("http://tempuri.org/");
var SoapBody = input.Descendants(xns + "getResult").First().ToString();
but I am also getting namespace tempuri appended in getresult tag, which I don't want or any other way to achieve it ?

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication169
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(xml);
XElement results = doc.Descendants().Where(x=> x.Name.LocalName == "getResult").FirstOrDefault();
XNamespace ns = results.GetDefaultNamespace();
string id = (string)results.Element(ns + "Id");
Dictionary<string, string> au = results.Descendants(ns + "au").FirstOrDefault().Elements()
.GroupBy(x => x.Name.LocalName, y => (string)y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}

Related

Replace the value by relying on the existing value in XML file

This is a sample XML file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Automation Test</string>
<string name="current_data_state_incoming_call">Incoming Call</string>
<string name="current_data_state_outgoing_call">Outgoing Call</string>
<string name="current_data_state_missed_call">Missed Call</string>
<string name="current_data_state_photo">Photo</string>
<string name="current_data_state_video">Video</string>
<string name="current_data_state_mp3">MP3</string>
<string name="current_data_state_voice_memo">Voice Memo</string>
<string name="current_data_state_phone_book">Phone Book</string>
<string name="current_data_state_phone_booksim">Phone Book(SIM)</string>
<string name="current_data_state_etc">Etc</string>
<string name="current_data_state_schedule">S Planner</string>
</resources>
I have a large file XML file and I want to replace the values in elements depending on their original value.
For example, I want to replace "Outgoing Call" with another word.
I tried this code:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");
XmlElement root = xdoc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("string");
for (int i = 0; i < elemList.Count; i++)
{
xdoc.Save("strings.xml");
if (elemList[i].InnerText == "Incoming Call")
{
// xdoc.LoadXml(File.ReadAllText("strings.xml").Replace(elemList[i].InnerText, "صندوق"));
// MessageBox.Show(elemList[i].InnerText);
elemList[i].SelectSingleNode("resources/string").InnerText="مكالمات قادمة";
xdoc.Save("strings.xml");
}
}
and this code
XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");
XmlNodeList aNodes = xdoc.SelectNodes("resources/string");
foreach (XmlNode node in aNodes)
{
XmlNode child1 = node.SelectSingleNode("string");
if(child1.InnerText == "Incoming Call")
{
child1.InnerText = "اتصالات قادمة";
}
}
xdoc.Save("strings.xml");
I can not replace the value.
===================================
thanx i solve my prob
var root2 = new XmlDocument();
root2.Load("strings.xml");
var root = new XmlDocument();
root.Load("strings2.xml");
foreach (XmlNode e1 in root2.GetElementsByTagName("string"))
{
string a = e1.Attributes["name"].Value;
foreach (XmlNode ee in root.GetElementsByTagName("string"))
{
string b = ee.Attributes["name"].Value;
if (a == b)
{
e1.FirstChild.Value = ee.FirstChild.Value;
}
}
}
root.Save("strings.xml");
I would use LINQ to XML for this. It makes all kinds of things much simpler than XmlDocument. Here's a complete example to perform a replacement (loading input.xml and writing output.xml):
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("input.xml");
ReplaceValue(doc, "Outgoing Call", "Other value");
doc.Save("output.xml");
}
static void ReplaceValue(XDocument doc, string original, string replacement)
{
foreach (var element in doc.Descendants("string").Where(x => x.Value == original))
{
element.Value = replacement;
}
}
}
You could easily change the method to throw an exception if it didn't find the value you were trying to replace, or if it found more than one element.
An alternative to replacing by value would be to replace by the name attribute, which would be a trivial change:
static void ReplaceNamedValue(XDocument doc, string name, string replacement)
{
foreach (var element in doc.Descendants("string")
.Where(x => (string) x.Attribute("name") == name))
{
element.Value = replacement;
}
}
You'd then call it like this:
ReplaceNamedValue(doc, "current_data_state_outgoing_call", "Other value");
You may want to create file on xml on the fly instead of replace. I prefer using the newer Net library xml linq (XDocument) rather than the older version XmlDocument. Here is an example of the code I would use :
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 ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources></resources>";
XDocument doc = XDocument.Parse(ident);
XElement resources = doc.Root;
resources.Add(new XElement("string", new object[] {
new XAttribute("name","app_name"),
"Automation Test"
}));
resources.Add(new XElement("string", new object[] {
new XAttribute("name","current_data_state_incoming_call"),
"مكالمات قادمة"
}));
}
}
}
Here is code for replacement
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);
XElement resource = doc.Root;
Dictionary<string, XElement> dict = resource.Elements()
.GroupBy(x => (string)x.Attribute("name"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
if(dict.ContainsKey("app_name"))
{
dict["app_name"].SetValue("Automation Test");
}
if (dict.ContainsKey("current_data_state_incoming_call"))
{
dict["current_data_state_incoming_call"].SetValue("مكالمات قادمة");
}
}
}
}

Retrieving Xml Attribute Value in C#

I'm new to C# & I'm trying to read XML attribute from XML file in my Asp.net web project, when i retrieve attribute content i get this result :
"System.XML.Attribute;"
here is XML file:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<!--creating XML file-->
<Document PagesInDocument="1" Filename="YahyaXML">
<Page Filename="YahyaXML" ZonesInPage="1" PageID="0">
<Zone TextLinesInZone="2" zoneLRY="558" zoneLRX="1202"
zoneULY="3" zoneULX="886" ZoneID="0">
<TextLine Content="aaaaaaaaaaa" TextLineID="0"/>
<TextLine Content="aaaaaaaaaaaaaaaaaa" TextLineID="1"/>
</Zone>
</Page>
</Document>
Here is my c# code:
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\Program Files (x86)\NovoDynamics\NovoVerus\api\examples\C#Samples\WebAppTest\Uploads\test-ht.xml");
StringBuilder Content_Value = new StringBuilder();
XmlNodeList aNodes = doc.SelectNodes("/Document/Page/Zone");
XmlNodeList bNodes = doc.SelectNodes("/Document/Page/Zone/TextLine");
foreach (XmlNode aNode in aNodes)
{
XmlAttribute ULX_xml = aNode.Attributes["zoneULX"];
XmlAttribute ULY_xml = aNode.Attributes["zoneULY"];
XmlAttribute LRX_xml = aNode.Attributes["zoneLRX"];
XmlAttribute LRY_xml = aNode.Attributes["zoneLRY"];
if (ULX_xml.Value == TextBox5.Text && ULY_xml.Value == TextBox6.Text && LRX_xml.Value == TextBox7.Text && LRY_xml.Value == TextBox8.Text )
{
foreach (XmlNode bNode in bNodes)
{
//XmlAttribute ContentAttribute = bNode.Attributes["Content"];
if (bNode.Attributes["Content"].Value != null)
{
Content_Value.Append(bNode.Attributes["Content"].Value.ToString());
}
}
Content_Value.Append("\n");
}
}
TextBox9.Text = Content_Value.ToString();
Your code works. Try change first string in your xml file to:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
More: https://msdn.microsoft.com/en-us/library/ms256048(v=vs.120).aspx
Using xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
reader.ReadLine(); //skip identification
XDocument doc = XDocument.Load(reader);
var results = doc.Descendants("Page").Select(x => new
{
filename = (string)x.Attribute("Filename"),
page = (int)x.Attribute("ZonesInPage"),
id = (int)x.Attribute("PageID"),
zones = x.Elements("Zone").Select(y => new {
textLines = (int)y.Attribute("TextLinesInZone"),
ulx = (int)y.Attribute("zoneULX"),
uly = (int)y.Attribute("zoneULY"),
lrx = (int)y.Attribute("zoneLRX"),
lry = (int)y.Attribute("zoneLRY"),
textLine = y.Elements("TextLine").Select(z => new {
content = (string)z.Attribute("Content"),
id = (int)z.Attribute("TextLineID")
}).ToList()
}).ToList()
}).ToList();
}
}
}

How to get all attribute names from selected XML node in C#

This is my XML file. I need to select one test element and get all attributes name from its result child nodes.
<?xml version="1.0" encoding="UTF-8"?>
<summary>
<test>
<id>test 1</id>
<result value="-45">330</result>
<result value="0">300</result>
<result value="45">340</result>
</test>
<test>
<id>test 3</id>
<result value="-45">330</result>
<result value="0">300</result>
<result value="45">340</result>
</test>
</summary>
I wrote below code. but repeat same values and I want to stop it.
XmlDocument xd = new XmlDocument();
xd.Load(_xmlFilePath);
XmlNodeList nodelist = xd.GetElementsByTagName("result");
foreach (XmlNode node in nodelist)
{
string attrVal = node.Attributes["value"].Value;
Console.WriteLine(attrVal);
}
Any suggestion is appreciated.
Thanks.
You can use LINQ to Xml with XDocument class
var doc = XDocument.Load(_xmlFilePath);
var distinctResults = doc.Descendants("result")
.Select(element => element.Attribute("value").Value)
.Distinct();
foreach(var result in distinctResults)
{
Console.WriteLine(result);
}
Or with using of HashSet<string>
var results = doc.Descendants("result")
.Select(element => element.Attribute("value").Value);
var distinctResults = new HashSet<string>(results);
foreach(var result in distinctResults)
{
Console.WriteLine(result);
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication34
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string id = "test 1";
var results = doc.Descendants("test").Where(x => (string)x.Element("id") == id).FirstOrDefault().Elements("result").Select(x => new
{
angle = (int)x.Attribute("value"),
length = (int)x
}).ToList();
}
}
}

get information from xml node using agsxmpp library

<query xmlns="urn:xmpp:dialogueHistory">
<dialogueHistory id="4d38f289-9">
<MessageID>26164</MessageID>
<messageText>Fhh</messageText>
<msgDate>11/25/2016 6:30:39 AM</msgDate>
<unReadCount>0</unReadCount>
</dialogueHistory>
</query>
get information of messageid,messagetext
how can I get the information from the above xml using agsxmpp library
namespace is agsXMPP.Xml.Dom
You need to specify the namespace. Using xml linq
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);
List<XElement> dialogueHistory = doc.Descendants().Where(x => x.Name.LocalName == "dialogueHistory").ToList();
XNamespace ns = dialogueHistory.FirstOrDefault().GetDefaultNamespace();
var results = dialogueHistory.Select(x => new {
id = (string)x.Attribute("id"),
messageId = (int)x.Element(ns + "MessageID"),
messageText = (string)x.Element(ns + "messageText"),
messageDate = (DateTime)x.Element(ns + "msgDate"),
unReadCount = (int)x.Element(ns + "unReadCount")
}).ToList();
}
}
}

Reading XML and Save into Excel C#

I having XML as follow and I need to read this XML and get specific element in the XML and save into excel.
Below is my XML File :
<?xml version="1.0" encoding="UTF-8"?>
<ns1:BookTestXMLExport StartTime="2016-09-20T12:58:15.000+07:00" scanTime="2016-09-20T12:58:15.000+07:00" scanStatus="Pass">
<ns1:MachineXML barCode="ISN-1000500213" Revision="2016A" bookType="Novel"/>
<ns1:StationXML scannerName="HP4512745" stage="v810"/>
<ns1:ScanXML name="32:2:165:1">
<ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228000_9_0.jpg">
<ns1:BorrowXML packageId="NIL" userId="NIL" name="NIL"/>
<ns1:BookXML name="GrayDay" desc="Love Story"/>
</ns1:IndictmentXML>
</ns1:ScanXML>
<ns1:ScanXML name="35:23:165:1">
<ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228001_9_0.jpg">
<ns1:BorrowXML packageId="NIL" userId="8799" name="Sharon"/>
<ns1:BookXML name="Harry Potter" desc="Magic"/>
</ns1:IndictmentXML>
</ns1:ScanXML>
</ns1:BookTestXMLExport>
Below is the expected result:
Expected Result
Can anyone guide me on this.
Try this to parse file. You still need to save as excel.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication14
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement bookTestXMLExport = doc.Descendants().Where(x => x.Name.LocalName == "BookTestXMLExport").FirstOrDefault();
XNamespace ns = bookTestXMLExport.GetNamespaceOfPrefix("ns1");
var results = doc.Descendants(ns + "BookTestXMLExport").Select(x => new
{
scanStatus = (string)x.Attribute("scanStatus"),
barCode = (string)x.Element(ns + "MachineXML").Attribute("barCode"),
ScanXML = x.Elements(ns + "ScanXML").Select( y => new {
name = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("name"),
desc = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("desc")
}).ToList()
}).ToList();
}
}
}

Categories

Resources