XML Load repeated elements using c# - c#

Is that possible to loop element with the same orientation of fields.
<?xml version="1.0" encoding="utf-8"?>
<xml>
<document>
<sls>
<ppsitecode>0062</ppsitecode>
<ppsitedesc><![CDATA[AAAAAAA]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
<ppsitecode>0269</ppsitecode>
<ppsitedesc><![CDATA[BBBBBBB]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
<ppsitecode>2546</ppsitecode>
<ppsitedesc><![CDATA[CCCCCCC]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
</sls>
</document>
</xml>
Using the xml file above. Please refer to the desire output below:
ppsitecode ppsitedesc ppqty ppunit
0062 AAAAAAA 1.00 C24
0269 BBBBBBB 1.00 C24
2546 CCCCCCC 1.00 C24

Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication83
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement sls = doc.Descendants("sls").FirstOrDefault();
DataTable dt = new DataTable();
string[] columns = sls.Elements().Select(x => x.Name.LocalName).Distinct().ToArray();
foreach (string column in columns)
{
dt.Columns.Add(column, typeof(string));
}
DataRow newRow = null;
foreach (XElement element in sls.Elements())
{
string columnName = element.Name.LocalName;
if (columnName == "ppsitecode") newRow = dt.Rows.Add();
newRow[columnName] = (string)element;
}
}
}
}

Related

Getting values of both attribute and element in an xml

I have the following xml
<lists>
<list Group="3">More_lists_go_here</list>
</lists>
What I want is both the list element value which is More_lists_go_here and the Group attribute value which is 3.
What I have tried so far is
XmlDocument doc = new XmlDocument();
doc.LoadXml("<list Group=\"3\">More_lists_go_here</list>");
XmlElement root = doc.DocumentElement;
string value = root.Descendants("lists").Elements("list").Select(x => (string)x.Attribute("Group")).ToList();
what that gets me is
value = 3
what I want is both 3 and More_lists_go_here for string value
Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string input = "<lists><list Group=\"3\">More_lists_go_here</list></lists>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("list").Select(x => new { group = (string)x.Attribute("Group"), value = (string)x }).ToList();
}
}
}

How to get value from XML file

Given the following XML file:
<root>
<country>
<name></name>
<locationOU>null</location>
</country>
<country>
<name>Sweden</name>
<locationOU>Some Value</locationOU>
</country>
<country>
<name>Lithuania</name>
<locationOU>Some Value</locationOU>
</country>
<country>
<name>Belgium</name>
<locationOU>Some Value</locationOU>
</country>
</root>
How do I get the value of locationOU based on name value eg. name = Sweden?
You can work with XPath via XPathSelectElement(XNode, String).
using System.Xml.Linq;
using System.Xml.XPath;
// Read XML file
XDocument root = XDocument.Load(/* Your XML file path */);
// Read XML from string
// XDocument root = XDocument.Parse(xml);
XElement result = root.XPathSelectElement("/root/country[name='Sweden']");
string locationOU = result.Element("locationOU").Value;
Demo # .NET Fiddle
I like using xml linq with a dictionary :
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
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("country")
.GroupBy(x => (string)x.Element("name"), y => (string)y.Element("locationOU"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string sweedenLocation = dict["Sweden"];
}
}
}
XDocument doc = XDocument.Parse(XML_TEXT);
XElement rootElement = doc.XPathSelectElement("root");
var countries = rootElement?.Descendants().Where(e => e.Name.LocalName.Equals("country"));
var yourCountry = countries.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals("locationOU") && d.Value == "Sweden");
You can use XPath with above answers #Yong Shun
Or You can use DataSet as bellow:
DataSet ds=new DataSet();
ds.readXml(filename);
DataTable dt=ds.Tables[0];
string name="Sweden";
foreach(DataRow dr in dt.Select(String.Format("name='{0}'",name))
{
string locationOU=dr["locationOU"].toString();
}

c# - Select node in xmlDocument

I have an XML with this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Dossiers xmlns:ns2="http://www.dat.de/vxs" source="SD3" type="completeEvaluation">
<ns2:Dossier>
<ns2:Vehicle>
<ns2:VehicleIdentNumber>aaaaaaaaaa</ns2:VehicleIdentNumber>
<ns2:Equipment>
<ns2:OriginalEquipmentValueGross origin="dat">16206.00</ns2:OriginalEquipmentValueGross>
<ns2:SeriesEquipment>
<ns2:EquipmentPosition>
<ns2:DatEquipmentId>15201</ns2:DatEquipmentId>
<ns2:Description>lorem ipsum</ns2:Description>
</ns2:EquipmentPosition>
<ns2:EquipmentPosition>
<ns2:DatEquipmentId>17602</ns2:DatEquipmentId>
<ns2:Description>lorem ipsum</ns2:Description>
</ns2:EquipmentPosition>
...
</ns2:SeriesEquipment>
</ns2:Vehicle>
<ns2:Vehicle>
....
</ns2:Vehicle>
</ns2:Dossier>
</ns2:Dossiers>
With this code I have obtained the ns2:VehicleIdentNumber value:
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlFileContent);
var xmlNodeList = xml.GetElementsByTagName("ns2:Vehicle");
foreach (XmlElement xmlElement in xmlNodeList)
{
var telaio = xmlElement["ns2:VehicleIdentNumber"];
}
but how can I get ns2:OriginalEquipmentValueGross value and ns2:Description value?
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);
XElement root = doc.Root;
XNamespace ns2 = root.GetNamespaceOfPrefix("ns2");
var results = doc.Descendants(ns2 + "Vehicle").Select(x => new
{
vehicleIdentNumber = (string)x.Element(ns2 + "VehicleIdentNumber"),
originalEquipmentValueGross = (string)x.Descendants(ns2 + "OriginalEquipmentValueGross").FirstOrDefault()
}).ToList();
}
}
}
It should be more or less the same of what you already have:
var xmlNodeList = xml.GetElementsByTagName("ns2:Vehicle");
foreach (XmlElement xmlElement in xmlNodeList)
{
var telaio = xmlElement["ns2:VehicleIdentNumber"];
var equipment = xmlElement["ns2:Equipment"];
var originalEquipmentValueGross = equipment["ns2:OriginalEquipmentValueGross"].InnerText;
foreach (XmlElement equipmentPosition in equipment["ns2:SeriesEquipment"].GetElementsByTagName("ns2:EquipmentPosition"))
{
var description = equipmentPosition["ns2:Description"].InnerText;
}
}

Convert XML to formatted plain text issue

I have the following XML and i want to convert the contents to something along the lines of the following format.
PatientId: 123455, IdScheme: Test ....
<?xml version="1.0"?>
<gls:TheDocument xmlns:pbr="http://www.something.com"
xmlns:gls="http://www.testsomething.com"
xmlns:cnr="http://www.organisation.com"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="2.8">
<gls:PatientDem>
<cnr:PatientId>
<cnr:IdValue>123455</cnr:IdValue>
<cnr:IdScheme>TEST</cnr:IdScheme>
<cnr:IdType>PRN</cnr:IdType>
</cnr:PatientId>
<cnr:PatientName>
<cnr:Name>
<cnr:Title>Mr</cnr:Title>
<cnr:GivenName>Joe</cnr:GivenName>
<cnr:FamilyName>Wood</cnr:FamilyName>
</cnr:Name>
<cnr:NameType>Current Name</cnr:NameType>
</cnr:PatientName>
<cnr:PatientAddress>
<cnr:Address>
<cnr:AddressLine>57 High Street</cnr:AddressLine>
<cnr:AddressLine>London</cnr:AddressLine>
</cnr:Address>
<cnr:PostCode>WC1E 7HU</cnr:PostCode>
<cnr:AddressType>Current Residence</cnr:AddressType>
</cnr:PatientAddress>
<cnr:DateOfBirth>1969-11-02</cnr:DateOfBirth>
<cnr:Sex>M</cnr:Sex>
</gls:PatientDem>
<pbr:PatientAdminRef>
<pbr:Referrer>
<pbr:RefGP>
<cnr:GpcpName>
<cnr:FullName>DR SMITH</cnr:FullName>
</cnr:GpcpName>
<cnr:TheOrganisation>
<cnr:OrganisationId>
<cnr:IdValue>52522</cnr:IdValue>
<cnr:IdScheme>PracticeID</cnr:IdScheme>
<cnr:IdType>Healthcare Organisation</cnr:IdType>
</cnr:OrganisationId>
<cnr:OrganisationName>National Health
Service</cnr:OrganisationName>
<cnr:OrganisationAddress>
<cnr:TheAddress>
<cnr:AddressLine1>Centre House</cnr:AddressLine1>
<cnr:AddressLine2>799 Chichester
Street</cnr:AddressLine2>
<cnr:AddressLine3>London</cnr:AddressLine3>
</cnr:TheAddress>
<cnr:AddressType>Practice Address</cnr:AddressType>
</cnr:OrganisationAddress>
<cnr:OrganisationTelecom>
<cnr:TelephoneNumber>016190542350</cnr:TelephoneNumber>
<cnr:TeleType>Voice</cnr:TeleType>
</cnr:OrganisationTelecom>
</cnr:TheOrganisation>
</pbr:RefGP>
</pbr:Referrer>
</pbr:PatientAdminRef>
</gls:TheDocument>
So is it possible to do this? I had a go at doing this but I know for a fact i am doing it wrong as it cannot produce the result i want so any help will be much appreciated:
C# Code
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace glsNs = root.GetNamespaceOfPrefix("gls");
XNamespace cnrNS = root.GetNamespaceOfPrefix("cnr");
XNamespace pbrNS = root.GetNamespaceOfPrefix("pbr");
var output = new StringBuilder();
foreach (var result in doc.Descendants(gls + "PatientDem").Select(x => new {
Key = (string)x.Name.LocalName,
Value = x.Value
}))
{
output.AppendLine($"{result.key} : {result.value}");
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace cnrNs = root.GetNamespaceOfPrefix("cnr");
var results = doc.Descendants(cnrNs + "PatientId").Select(x => new {
value = (string)x.Element(cnrNs + "IdValue"),
scheme = (string)x.Element(cnrNs + "IdScheme")
}).ToList();
}
}
}

Grab xml value using XmlDocument

I want to grab UPC value from the following XML example node, but the current doc.SelectNodes fails to grab that value. I am using XmlDocument to process my XML. Can you fix my code to grab UPC value? What am I doing wrong here?
C# Code:
string responseStr = new StreamReader(responseStream).ReadToEnd();
responseStream.Flush();
responseStream.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseStr);
if (doc.GetElementsByTagName("Ack").Item(0).InnerText != "Failure")
{
string UPC = doc.SelectNodes("Item").Item(0).SelectNodes("UPC").Item(0).InnerText;
}
XML Sample:
<?xml version="1.0" encoding="UTF-8"?>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2018-07-28T08:18:10.048Z</Timestamp>
<Ack>Success</Ack>
<Version>1069</Version>
<Build>E1069_CORE_API_18748854_R1</Build>
<Item>
<ProductListingDetails>
<ISBN>Not Applicable</ISBN>
<UPC>853365007036</UPC>
<EAN>0853365007036</EAN>
<BrandMPN>
<Brand>UpCart</Brand>
<MPN>MPCB-1DX</MPN>
</BrandMPN>
<IncludeeBayProductDetails>true</IncludeeBayProductDetails>
</ProductListingDetails>
</Item>
</GetItemResponse>
You have a namespace that must be used to get values. Here is the easy way 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);
XNamespace ns = doc.Root.GetDefaultNamespace();
string UPC = (string)doc.Descendants(ns + "UPC").FirstOrDefault();
}
}
}
If you have nulls use this
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);
XNamespace ns = doc.Root.GetDefaultNamespace();
var upcs = doc.Descendants(ns + "UPC");
if (upcs != null)
{
string upc = (string)upcs.FirstOrDefault();
}
}
}
}

Categories