Query for unique id with XDocument - c#

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 />");
}
}
}

Related

How to read file string xml file with prefix

This is mycode. I want to get elements in string xml but i didn't. Please help me.
$
string xml = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><GetCustomerInfoResponse xmlns='http://tempuri.org/'><GetCustomerInfoResult xmlns:a='http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><a:Address>137 Phường Tân Xuyên</a:Address><a:Bills><a:BillInfo><a:Amount>1516682</a:Amount><a:BillCode>170810TD</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045487</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo><a:BillInfo><a:Amount>89000</a:Amount><a:BillCode>170810DC</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045487</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo><a:BillInfo><a:Amount>148028</a:Amount><a:BillCode>170810VC</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045488</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo></a:Bills><a:CustomerCode>PB14010040801</a:CustomerCode><a:DanhSo>44900L36</a:DanhSo><a:MaSoThue></a:MaSoThue><a:MaTram></a:MaTram><a:Name>Cơ Sở Mộc Thành Tài</a:Name><a:NganhNghe></a:NganhNghe><a:PhienGCS></a:PhienGCS><a:Session></a:Session><a:SoCongTo>14226305</a:SoCongTo><a:SoGhiChiSo>A1010D001</a:SoGhiChiSo></GetCustomerInfoResult></GetCustomerInfoResponse></s:Body></s:Envelope>";
window.jQuery
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var ns = new XmlNamespaceManager(new NameTable());
// XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
// ns.AddNamespace("xmlns","'http://tempuri.org/'");
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC");
ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
string xpath = "s:Envelope/s:Body/GetCustomerInfoResponse/GetCustomerInfoResult";
// string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath,ns);
;
foreach (XmlNode childrenNode in nodes)
{
Console.Write(childrenNode.SelectSingleNode("a:Address",ns).InnerXml);
Console.Write("\n");
}
Unfortunately, in a namespaced document, you can't use XPath with the default namespace. See this answer for more info.
This works:
var ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC");
ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
//Add a prefix for the default namespace for GetCustomerInfoResponse and GeteCustomerInforResult
ns.AddNamespace("t","http://tempuri.org/");
string xpath = "s:Envelope/s:Body/t:GetCustomerInfoResponse/t:GetCustomerInfoResult";
var nodes = xmlDoc.SelectNodes(xpath, ns);
foreach (XmlNode childrenNode in nodes)
{
Console.Write(childrenNode.SelectSingleNode("a:Address", ns).InnerXml);
Console.Write("\n");
}

Can't figure out how to read xml data in Visual Studio C#

I'm not sure how to read out the data from a XML file.
The XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Lijsten>
<Lijst>
<Titel>Discipline</Titel>
<Waardes>Elektro</Waardes>
<Waardes>Mechanisch</Waardes>
<Waardes>Civiel</Waardes>
<Waardes>Proces</Waardes>
</Lijst>
<Lijst>
<Titel>Soort</Titel>
<Waardes>Tekening</Waardes>
<Waardes>Tekst doc</Waardes>
<Waardes>Afbeelding</Waardes>
</Lijst>
<Lijst>
<Titel>Afdruk</Titel>
<Waardes>Landscape</Waardes>
<Waardes>Portrait</Waardes>
</Lijst>
<Lijst>
<Titel>Kleur</Titel>
<Waardes>Kleur</Waardes>
<Waardes>Zwart</Waardes>
</Lijst>
<Lijst>
<Titel>Kader</Titel>
<Waardes>Aanwezig</Waardes>
<Waardes>Niet aanwezig</Waardes>
</Lijst>
</Lijsten>
I'm trying to create a radio-button menu for every "Lijst".
What I've got so far(not much):
XmlTextReader reader = new XmlTextReader("iniFile.xml");
while (reader.Read())
{
while (reader.ReadToFollowing("Lijst"))
{
while (reader.ReadToFollowing("Titel"))
{
}
}
}
If you don't want to read using XElement, you can use XmlDocument and XPath
Take a look at this example, to get all titles:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Titel");
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
or, to get all Lijst nodes and then iterate through them to get title and warde values
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Lijst");
foreach (XmlNode node in nodes)
{
Console.WriteLine("this is List with title: " + node["Titel"].InnerText);
Console.WriteLine("it contains wardes: " + node["Titel"].InnerText);
XmlNodeList wardeNodes = node.SelectNodes("Waardes");
foreach (XmlNode wNode in wardeNodes)
{
Console.WriteLine(" - " + wNode.InnerText);
}
}
With XElement class and LinqToXML:
XElement xml = XElement.Parse(xml);
var buttons = xml.Element("Lijsten")
.Elements()
.Select(p => new { Titel = p.Element("Titel").Value })
.ToArray();

Read Array in XML in C#

I'm trying to read arrays in an XML, but my code does not return results
XML :
<ArrayOfProductoModel
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>
Code :
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(content);
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
As I can read the array?
The problem is the imported namespace. You can ignore the namespace as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("*[local-name()='ProductoModel']");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("*[local-name()='descripcion']").InnerText);
}
Alternatively you can use an XmlNamespaceManager as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "http://schemas.datacontract.org/2004/07/WebApi.Models");
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("MYNS:ProductoModel", manager);
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("MYNS:descripcion", manager).InnerText);
}
Another solution is to use Linq to XML
var xml = #"<ArrayOfProductoModel
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
xmlns=""http://schemas.datacontract.org/2004/07/WebApi.Models"">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>";
var xDoc = XDocument.Parse(xml);
var ns = xDoc.Root.Name.Namespace;
var nodelist = xDoc.Element(ns + "ArrayOfProductoModel").Elements(ns + "ProductoModel");
foreach (var node in nodelist)
{
MessageBox.Show(node.Element(ns + "descripcion").Value);
}
Don't forget to put namespace in front of local name.
At first, I think problem in
xDoc.LoadXml(content);
You try:
xDoc.Load(filePathXml);
Second, I think problem in
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
You try:
XmlNode rootNode = doc.SelectSingleNode(#"/ArrayOfProductoModel");
var listProductModel = rootNode.SelectNodes(#"ProductoModel");
foreach (XmlNode node in listProductModel)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}

Navigate xml nodes;

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

Insert line in xml doc

I wanna insert in second line :
<?mso-application progid="Excel.Sheet"?>
but I'm started to think that it is impossible.
Here is my base code:
XmlDocument doc = new XmlDocument();
XmlReader reader = cmd.ExecuteXmlReader();
doc.LoadXml("<results></results>");
XmlNode newNode = doc.ReadNode(reader);
while (newNode != null)
{
doc.DocumentElement.AppendChild(newNode);
newNode = doc.ReadNode(reader);
}
Just Try like this
XmlNode XNode = doc.CreateProcessingInstruction("mso-application ", "progid=\"Excel.Sheet\"");
doc.AppendChild(XNode);
<?mso-application progid="Excel.Sheet"?> is a processing instruction not an element so you need to use the CreateProcessingInstruction Method

Categories

Resources