Can't pass XML using WSDL and escaping characters - c#

I'm really struggling to find a way to pass an XML string without escaping the characters in C#. I have a string below that needs to be passed into a call to a WSDL as a string.
<MyElement ElementId='xxxxxx'><Segments><Segment Status='1' SegmentId='xx1'/><Segment Status='1'
SegmentId='xx2'/></Segments></MyElement>
If I try to pass it has a string the characters are escaping characters such as '>'. I imported the WSDL in a .NET Console application. Here is what that string above is going into as I see using the Wizdler tool in chrome.
The entire message is this.
So my question is how in C# can I use the WSDL or even just do it manually to make the call to make this work
using (var client = new MemberService.MemberWebServiceSoapClient())
{
var xml = "<MyElement ElementId='xxxxxxx'><Segments><Segment Status='1' SegmentId='xx1'/><Segment
Status='1' SegmentId='xx2'/></Segments></MyElement>"
var send = client.Moving(xml);
}

Use 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)
{
string envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<Body>" +
"<Moving xmlns=\"http://www.retalix.com/HQLWebServices\">" +
"</Moving>" +
"</Body>" +
"</Envelope>";
XDocument doc = XDocument.Parse(envelope);
XElement moving = doc.Descendants().Where(x => x.Name.LocalName == "Moving").FirstOrDefault();
XNamespace ns = moving.GetDefaultNamespace();
string elementId = "xxxxxx";
List<Segment> segments = new List<Segment>() {
new Segment() { id = "xx1", status = 1},
new Segment() { id = "xx2", status = 1}
};
XElement xMyElement = new XElement(ns + "MyElement", new XAttribute("ElementId", elementId));
moving.Add(xMyElement);
XElement xSegments = new XElement(ns + "Segments");
xMyElement.Add(xSegments);
foreach (Segment segment in segments)
{
XElement xSegment = new XElement("Segment", new object[] {
new XAttribute("Status", segment.status),
new XAttribute("SegmentId", segment.id)
});
xSegments.Add(xSegment);
}
string sendXml = doc.ToString();
}
}
public class Segment
{
public string id { get; set; }
public int status { get; set; }
}
}

Related

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();
}
}
}

XML to String List

I have some code that I need to put into a string list in C# and I am reading this code from an XML files and the layout of it is something like below...
<?xml version="1.0"?>
<accountlist>
<main>
<account id="1" special_id="4923959">
<username>Adam</username>
<motto>Hello Everyone>
<money>1004</money>
<friends>394</friends>
<rareid>9</rareid>
<mission>10</mission>
</account>
</main>
</accountlist>
How can I put each account tag into a string list? from the first < account > to the < / account > tag?
Please do NOT tell me to go to the link below as it does NOT work!!
How to read a XML file and write into List<>?
So far I have tried the below code, and the string list just stays empty
XDocument doc = XDocument.Parse(this._accountsFile);
List<string> list = doc.Root.Elements("account")
.Select(element => element.Value)
.ToList();
this._accounts = list;
You'll have to use Descendants instead of Elements:
List<string> list = doc.Root.Descendants("account").Descendants()
.Select(element => element.Value)
.ToList();
Elements only returns child elements of the element (in case of the root element this means <main>).
Descendants returns the entire tree inside the element.
Also: You'll have to fix the tag <motto>Hello Everyone> to <motto>Hello Everyone</motto>
This will work on your example (but you need to close this tag <motto>Hello Everyone>
public List<string> GetAccountsAsXmlList(string filePath)
{
XmlDocument x = new XmlDocument();
x.Load(filePath);
List<string> result = new List<string>();
XmlNode currentNode;
foreach (var accountNode in x.LastChild.FirstChild.ChildNodes)
{
currentNode = accountNode as XmlNode;
result.Add(currentNode.InnerXml);
}
return result;
}
EDIT as an answer to your question:
Is there a way I can get the id and specal_id in a seperate string?
you can use currentNode.Attributes["YourAttributeName"].Value, to get the values.
assume you have class Account :
class Account
{
public string accountXml { get; set; }
public string Id { get; set; }
public string Special_id { get; set; }
}
Then :
public List<Account> GetAccountsAsXmlList(string filePath)
{
XmlDocument x = new XmlDocument();
x.Load(filePath);
List<Account> result = new List<Account>();
XmlNode currentNode;
foreach (var accountNode in x.LastChild.FirstChild.ChildNodes)
{
currentNode = accountNode as XmlNode;
result.Add(new Account
{
accountXml = currentNode.InnerXml,
Id = currentNode.Attributes["id"].Value,
Special_id = currentNode.Attributes["special_id"].Value,
});
}
return result;
}
Use XPath to get the account element first:
using System.Xml.XPath;
XDocument doc = XDocument.Parse(xml);
foreach(var account in doc.XPathSelectElements("accountlist/main/account")){
List<string> list = account.Descendants()
.Select(element => element.Value)
.ToList();
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication37
{
class Program
{
static void Main(string[] args)
{
string input =
"<?xml version=\"1.0\"?>" +
"<accountlist>" +
"<main>" +
"<account id=\"1\" special_id=\"4923959\">" +
"<username>Adam</username>" +
"<motto>" +
"Hello Everyone>" +
"<money>1004</money>" +
"<friends>394</friends>" +
"<rareid>9</rareid>" +
"<mission>10</mission>" +
"</motto>" +
"</account>" +
"</main>" +
"</accountlist>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("accountlist").Select(x => new {
id = x.Element("main").Element("account").Attribute("id").Value,
special_id = x.Element("main").Element("account").Attribute("special_id").Value,
username = x.Element("main").Element("account").Element("username").Value,
motto = x.Element("main").Element("account").Element("motto").FirstNode.ToString(),
money = x.Element("main").Element("account").Element("motto").Element("money").Value,
friends = x.Element("main").Element("account").Element("motto").Element("friends").Value,
rareid = x.Element("main").Element("account").Element("motto").Element("rareid").Value,
mission = x.Element("main").Element("account").Element("motto").Element("mission").Value,
}).ToList();
}
}
}

Get data from XML in simple way

I am using the following code to get data from the OData XML and its works ,
but I am not sure that I fully understand it so maybe there is a way to write it in simple way?
what i need is to get the property value which is in the first loop value = 0001 and text = approve and in the
second value = 0002 text = reject
The code
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
if (response.StatusCode == HttpStatusCode.OK)
{
string decisionOptions = ReadResponse(response);
XDocument document = XDocument.Parse(decisionOptions);
foreach (XElement element in document.Element(dns + "DecisionOptions").Elements(dns + "element"))
{
PropertyKeyRef decisionOption = new PropertyKeyRef();
decisionOption.PropertyValue = element.Element(dns + "DecisionKey").Value;
decisionOption.PropertyName = element.Element(dns + "DecisionText").Value;
dat.Add(decisionOption);
}
}
the XML
<?xml version="1.0" encoding="utf-8" ?>
- <d:DecisionOptions xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
- <d:element m:type="TAS.DecisionOption">
<d:InstanceID>007</d:InstanceID>
<d:DecisionKey>0001</d:DecisionKey>
<d:DecisionText>Approve</d:DecisionText>
<d:CommentMandatory>false</d:CommentMandatory>
<d:Nature>POSITIVE</d:Nature>
</d:element>
- <d:element m:type="TAS.DecisionOption">
<d:InstanceID>007</d:InstanceID>
<d:DecisionKey>0002</d:DecisionKey>
<d:DecisionText>Reject</d:DecisionText>
<d:CommentMandatory>true</d:CommentMandatory>
<d:Nature>NEGATIVE</d:Nature>
</d:element>
</d:DecisionOptions>
here how can do it in simple way using LINQ
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load("test.xml");
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
//in xml every element should have it's namespace for this reason I have to concatenate namespace with the name of element
var elementsRes = xdoc.Root.Elements(dns+"element").Select((elt) => new PropertyKeyRef { PropertyName = elt.Element(dns+"DecisionKey").Value.ToString(),PropertyValue = elt.Element(dns+"DecisionText").Value.ToString() }).ToList();
foreach (var item in elementsRes)
{
//your code for the result
}
}
}
public class PropertyKeyRef
{
public string PropertyName
{ get; set; }
public string PropertyValue
{ get; set; }
}
}
You have already achieved it in simplest way. Little bit of LINQ might improve readability (get away with foreach loop) but it's just syntactic sugar of what you have written.
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XDocument document = XDocument.Load("database.xml");
PropertyKeyRef decisionOption = new PropertyKeyRef();
decisionOption.PropertyValue = document.Descendants(dns + "DecisionKey")
.Select(node => node.Value).First();
decisionOption.PropertyName = document.Descendants(dns + "DecisionText")
.Select(node => node.Value).First();
dat.Add(decisionOption);

html table tag not matching closing body tag

I recently started C# a couple days ago (transitioning from Java) and am writing some codes to practice. This current program reads an xml file and outputs the content in an html table. I use Visual Studios IDE.
I get the error: The 'table' start tag does not match the end tag of 'body'. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Linq;
namespace XML
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the file name: ");
String fileName = Console.ReadLine();
Console.WriteLine("Enter output file");
String outFile = Console.ReadLine();
XDocument xml = XDocument.Load(Path.GetFullPath(outFile));
StreamWriter outf = new StreamWriter(Path.GetFullPath(outFile));
outputHTML(xml,outf);
outf.Close();
}
static void outputHTML(XDocument xml, StreamWriter outf)
{
outf.WriteLine("<!DOCTYPE html>");
outf.WriteLine("<html>");
outf.WriteLine("<body>");
outf.WriteLine("<table border='1'>");
while (xml.Root.HasElements)
{
outf.WriteLine("<tr>");
var products = from p in xml.Descendants("book")
select new
{
author = (String)p.Element("author"),
genre = (String)(String)p.Element("genre"),
title = (string)p.Element("title"),
price = (int)p.Element("price"),
publishDate = (String)p.Element("publish_date"),
Descrip = (String)p.Element(" ")
};
foreach (var product in products)
{
outf.WriteLine("<td>");
outf.WriteLine(product.author);
outf.WriteLine("</td>");
outf.WriteLine("<td>");
outf.WriteLine(product.title);
outf.WriteLine("</td>");
outf.WriteLine("<td>");
outf.WriteLine(product.genre);
outf.WriteLine("</td>");
outf.WriteLine("<td>");
outf.WriteLine(product.price);
outf.WriteLine("</td>");
outf.WriteLine("<td>");
outf.WriteLine(product.publishDate);
outf.WriteLine("</td>");
outf.WriteLine("<td>");
outf.WriteLine(product.Descrip);
outf.WriteLine("</td>");
}
outf.WriteLine("</tr>");
}
outf.WriteLine("</table>");
outf.WriteLine("</body>");
outf.WriteLine("</html>");
}
}
}
***Also, if anyone could recommend any programs to write to practice C#, that would be great.
Thanks
Please, for the love of god, don't write your own Html (or xml either). You are going to run into ALL sorts of problems, from encoding to mis-matching tags. Use the HTML Agility Pack to do all the formatting for you.
public string CreateHTML(XElement sourceXML)
{
//make the Html Agility Pack object
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
//parse through your xml
var products = sourceXML.Descendants("book")
.Select(x => new
{
author = x.Element("author").Value,
genre = x.Element("genre").Value,
title = x.Element("title").Value,
price = x.Element("price").Value,
publishDate = x.Element("publish_date").Value,
descrip = x.Element("description"),
});
//make and populate your table node
HtmlNode tableNode = HtmlNode.CreateNode("<table border='1'>");
foreach (var product in products)
{
tableNode.AppendChild(HtmlNode.CreateNode("<td>" + product.author + "</td>"));
tableNode.AppendChild(HtmlNode.CreateNode("<td>" + product.genre + "</td>"));
....
}
//create the html root and append the table node
doc.DocumentNode.AppendChild(HtmlNode.CreateNode("<html><body>"));
doc.DocumentNode.Element("html").Element("body").AppendChild(tableNode);
return doc.DocumentNode.InnerHtml;
}
You can then call it like this:
XElement sourceXML = XElement.Load(Path.GetFullPath(outFile));
string html = CreateHTML(sourceXML);

Categories

Resources