Create XML from SQL select query - c#

I am trying to create a xml from a SQL select, but I can not insert ":" (like cac:PartyTaxScheme), neither can put 2 data in one element, look element "cbc:CompanyID" (<cbc:CompanyID schemeName="31" schemeID="0" schemeAgencyID="195">900711000</cbc:CompanyID> ), how can I do it ?
Next is the example I want to expect:
<cac:PartyTaxScheme>
<cbc:RegistrationName>GRUPO FAM</cbc:RegistrationName>
<cbc:CompanyID schemeName="31" schemeID="0" schemeAgencyID="195">900711000</cbc:CompanyID>
<cbc:TaxLevelCode listName="48">O-23</cbc:TaxLevelCode>
<cac:RegistrationAddress>
<cbc:ID>11001</cbc:ID>
<cbc:CountrySubentityCode>11</cbc:CountrySubentityCode>
<cac:AddressLine>
<cbc:Line>CaLL 90</cbc:Line>
</cac:AddressLine>
<cac:Country>
<cbc:IdentificationCode>CO</cbc:IdentificationCode>
</cac:Country>
</cac:RegistrationAddress>
</cac:PartyTaxScheme>
Thanks a lot

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
{
static void Main(string[] args)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<cac:PartyTaxScheme xmlns:cac=\"URL1\" xmlns:cbc=\"URL2\">" +
"</cac:PartyTaxScheme>";
XDocument doc = XDocument.Parse(ident);
string registrationName = "GPUPO FAM";
string schemeName = "31";
string schemeID = "0";
string schemeAgencyID = "195";
string companyID = "900711000";
string listName = "48";
string taxLevelCode = "0-23";
string ID = "11001";
string countrySubentityCode = "11";
string address = "CaLL 90";
string identificationCode = "CO";
XElement partyTaxScheme = doc.Root;
XNamespace nsCac = partyTaxScheme.GetNamespaceOfPrefix("cac");
XNamespace nsCbc = partyTaxScheme.GetNamespaceOfPrefix("cbc");
XElement xRegistrationName = new XElement(nsCac + "RegistrationName", registrationName);
partyTaxScheme.Add(xRegistrationName);
XElement xCompanyID = new XElement(nsCbc + "CompanyID", new object[] {
new XAttribute("scnemeName", schemeName),
new XAttribute("schemeID", schemeID),
new XAttribute("schemeAgencyID", schemeAgencyID),
companyID
});
partyTaxScheme.Add(xCompanyID);
XElement xTaxLevelCode = new XElement(nsCbc + "TaxLevelCode", new object[] {
new XAttribute("listName", listName),
taxLevelCode
});
partyTaxScheme.Add(xTaxLevelCode);
XElement xRegistrationAddress = new XElement(nsCac + "RegistrationAddress");
partyTaxScheme.Add(xRegistrationAddress);
xRegistrationAddress.Add(new XElement(nsCbc + "ID", ID));
xRegistrationAddress.Add(new XElement(nsCbc + "CountrySubentityCode", countrySubentityCode));
xRegistrationAddress.Add(new XElement(nsCac + "AddressLine", new XElement(nsCbc + "Line", address)));
xRegistrationAddress.Add(new XElement(nsCac + "Country", new XElement(nsCbc + "IdentificationCode", countrySubentityCode)));
}
}
}

Related

C# Xdocument Xml get Element

I have a xml file that looks like this:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetAllArticlesResponse xmlns="http://www.borger.dk/2009/WSArticleExport/v1">
<GetAllArticlesResult xmlns:a="http://www.borger.dk/2009/WSArticleExport/v1/types" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:ArticleDescription>Test 1</a:ArticleDescription>
<a:ArticleDescription>Test 2</a:ArticleDescription>
</GetAllArticlesResult>
</GetAllArticlesResponse>
</s:Body>
</s:Envelope>
I'm trying to get all the articles, but can't get it to work.
XDocument doc = XDocument.Parse(soapResult);
IEnumerable<XElement> articles = doc.Root.Descendants("a:ArticleDescription");
This has work before, but because the element name as a : then it fails..
Any idea how to fix this.
Thanks for all the inputs.
I ended with::
XNamespace a = "http://www.borger.dk/2009/WSArticleExport/v1/types";
XDocument doc = XDocument.Parse(soapResult);
IEnumerable<XElement> articles = doc.Root.Descendants(a + "ArticleDescription");
List<Article> article = articles.Select(m => new Article()
{
ArticleID = m.Element(a + "ArticleID").Value.ToString(),
ArticleTitle = m.Element(a + "ArticleTitle").Value.ToString(),
ArticleUrl = m.Element(a + "ArticleUrl").Value.ToString(),
LastUpdated = m.Element(a + "LastUpdated").Value.ToString(),
PublishingDate = m.Element(a + "PublishingDate").Value.ToString()
}).ToList();
json = JsonConvert.SerializeObject(article);
Here's an alterante way:
var doc = XDocument.Load(xml);
XNamespace ns1 = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns2 = "http://www.borger.dk/2009/WSArticleExport/v1";
XNamespace ns3 = "http://www.borger.dk/2009/WSArticleExport/v1/types";
var result = doc.Element(ns1 + "Envelope")
.Element(ns1 + "Body")
.Element(ns2 + "GetAllArticlesResponse")
.Element(ns2 + "GetAllArticlesResult")
.Elements(ns3 + "ArticleDescription")
.Select(x => x.Value);
Or
var doc = XDocument.Load(xml);
var envelope = doc.Root;
var body = (XElement)envelope.FirstNode;
var getAllArticlesResponse = (XElement)body.FirstNode;
var getAllArticlesResult = (XElement)getAllArticlesResponse.FirstNode;
var articleDescriptions = getAllArticlesResult.Nodes().Cast<XElement>();
var result = articleDescriptions.Select(x => x.Value);
Here is easiest way using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication137
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string[] description = doc.Descendants().Where(x => x.Name.LocalName == "ArticleDescription").Select(x => (string)x).ToArray();
}
}
}
The prefix a: is a short-for of the namespace name "http://www.borger.dk/2009/WSArticleExport/v1/types", you can see that where the prefix is declared.
You can use namespace-aware XName's when querying:
var descriptions = doc.Root.Descendants(
XName.Get("ArticleDescription", "http://www.borger.dk/2009/WSArticleExport/v1/types"));
Of course you could store the namespaces you want in variables, you don't have to type them out every time.
You can also just look at the local names, if you're not worried about collisions.
var descriptions = doc.Root.Descendants().Where(x => x.Name.LocalName == "ArticleDescription");

Concatenate values from the same nodes for each employee individ in XML

I am beginner in programming. I have a scenario like this:
For each unique application member, I want to return a new XML that contains for each EMPLOYEE_MEMBER_INDIVID all concatenated values of EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION field.
Roles should be concatenated for each MEMBER_UNIQID from APPLICATION_MEMBER nodes.
<EMPLOYEE_MEMBER_INDIVID>
<EMPLOYEE_MEMBER_INDIVID_MAIN_DATA ENTITY="">
<EMPLOYEE_MEMBER_INDIVID_UNIQ_ID>096788</EMPLOYEE_MEMBER_INDIVID_UNIQ_ID>
<EMPLOYEE_MEMBER_INDIVID_NAME>Dina</EMPLOYEE_MEMBER_INDIVID_NAME>
<EMPLOYEE_MEMBER_INDIVID_SURNAME>Gomez</EMPLOYEE_MEMBER_INDIVID_SURNAME>
</EMPLOYEE_MEMBER_INDIVID_MAIN_DATA>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA ENTITY="">
<EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>Co-borrower</EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA ENTITY=""> <EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>Guarantor</EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA ENTITY="">
<EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>Mortgager individual</EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S>
</EMPLOYEE_MEMBER_INDIVID>
The output node should be:
<EMPLOYEE_MEMBER_INDIVID>
<EMPLOYEE_MEMBER_INDIVID_MAIN_DATA ENTITY="">
<EMPLOYEE_MEMBER_INDIVID_UNIQ_ID>096788</EMPLOYEE_MEMBER_INDIVID_UNIQ_ID>
<EMPLOYEE_MEMBER_INDIVID_NAME>Dina</EMPLOYEE_MEMBER_INDIVID_NAME>
<EMPLOYEE_MEMBER_INDIVID_SURNAME>Gomez</EMPLOYEE_MEMBER_INDIVID_SURNAME>
</EMPLOYEE_MEMBER_INDIVID_MAIN_DATA>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S>
<EMPLOYEE_MEMBER_INDIVID_ROLE_DATA ENTITY="">
<EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>Co-borrower / Guarantor / Mortgager individual</EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA>
</EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S>
</EMPLOYEE_MEMBER_INDIVID>
My code is:
static void Main(string[] args)
{
try
{
//Create A XML Document Of Response String
XmlDocument xmlDoc = new XmlDocument();
//Read the XML File
XmlNodeList nodeList2 = xmlDoc.SelectNodes("//EMPLOYEE_MEMBER_S/EMPLOYEE_MEMBER" +
"[(EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION ='Borrower' " +
"or EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION='Mortgager' " +
"or EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION='Co-borrower')]");
List<string> baseMemberUNIQ_IDs = new List<string>();
List<LoanMember> infos = new List<LoanMember>();
XmlNodeList baseMembersList = xmlDoc.SelectNodes("//APPLICATION_MEMBERS/APPLICATION_MEMBER[ROLE='Borrower' or ROLE='Mortgager individual' or ROLE='Co-borrower']");
foreach (XmlNode xmlNode in baseMembersList)
{
baseMemberUNIQ_IDs.Add(xmlNode["MEMBER_UNIQ_ID"].InnerText);
}
var distinctBaseMembersUNIQ_ID = baseMemberUNIQ_IDs.Distinct();
foreach (var UNIQ_ID in distinctBaseMembersUNIQ_ID)
{
XmlNodeList nodeList = xmlDoc.SelectNodes("//EMPLOYEE_MEMBER_S/EMPLOYEE_MEMBER" +
"[(EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION ='Borrower' " +
"or EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION='Mortgager individual' " +
"or EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S/EMPLOYEE_MEMBER_INDIVID_ROLE_DATA/EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION='Co-borrower') " +
"and EMPLOYEE_MEMBER_INDIVID/EMPLOYEE_MEMBER_INDIVID_MAIN_DATA/EMPLOYEE_MEMBER_INDIVID_UNIQ_ID=" + UNIQ_ID.ToString() + "]");
foreach (XmlNode xmlNode2 in nodeList)
{
String ROLE = "";
foreach (XmlNode childNode in xmlNode2)
{
ROLE = childNode.ChildNodes[0].InnerXml;
Console.WriteLine("CONCATED ROLES ARE " + ROLE);
// All roles of each employee individ should be concatenated inside the first node EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION node, Other nodes shoud be removed/
}
}
}
}
catch
{
throw;
}
Console.ReadKey();
}
}
In the following url is input document XML: https://codebeautify.org/xmlviewer/cb7a26e5
Thank you for your help!
Try following 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> EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S = doc.Descendants("EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S").ToList();
foreach (XElement EMPLOYEE_MEMBER_INDIVID_ROLE_DATA in EMPLOYEE_MEMBER_INDIVID_ROLE_DATA_S)
{
string[] roles = EMPLOYEE_MEMBER_INDIVID_ROLE_DATA.Descendants("EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION").Select(x => (string)x).ToArray();
XElement newEMPLOYEE_MEMBER_INDIVID_ROLE_DATA = new XElement("EMPLOYEE_MEMBER_INDIVID_ROLE_DATA", new object[] {
new XAttribute("ENTITY", ""),
new XElement("EMPLOYEE_MEMBER_INDIVID_ROLE_ON_APPLICATION", string.Join(" / ", roles))
});
EMPLOYEE_MEMBER_INDIVID_ROLE_DATA.ReplaceWith(newEMPLOYEE_MEMBER_INDIVID_ROLE_DATA);
}
}
}
}

Adding a new node (taking value from another xml file) inside a certain parent node?

I'm trying to create a program having the following steps:
1) Get all xml files from a user given path
2) Open each of the files (if any) and search for nodes <institution> where it is in the format <funding-source><institution-wrap><institution>...</institution></institution-wrap></funding-source>
3) Get the value of the nodes <institution> and search the exact value in the database xml inside the nodes <skosxl:literalForm xml:lang="...">
4) If found, get the attribute value of its parent node <skos:Concept rdf:about="..."> minus the string http://dx.doi.org/
5) Add a node <institution-id institution-id-type="fundref"> in the xml file after the <institution> node with the value like <funding-source><institution-wrap><institution>...</institution><institution-id institution-id-type="fundref">VALUE of the rdf:about attribute</institution-id></institution-wrap></funding-source>
Here is a sample input file and the desired output for that file.
What I have tried:
string pathToUpdatedFile = #"D:\test\Jobs";
var files=Directory.GetFiles(pathToUpdatedFile,"*.xml");
foreach (var file in files)
{
var fundingDoc = XDocument.Load(#"D:\test\database.xml");
XNamespace rdf=XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
XNamespace skosxl = XNamespace.Get("http://www.w3.org/2008/05/skos-xl#");
XNamespace skos=XNamespace.Get("http://www.w3.org/2004/02/skos/core#");
var targetAtt = fundingDoc.Descendants(skos+"Concept").Elements(skosxl+"prefLabel")
.ToLookup(s => (string)s.Element(skosxl+"literalForm"), s => (string)s.Parent.Attribute(rdf+"about"));
XDocument outDoc = XDocument.Parse(File.ReadAllText(file),LoadOptions.PreserveWhitespace);
foreach (var f in outDoc.Descendants("funding-source").Elements("institution-wrap"))
{
if (f.Element("institution-id") == null)
{
var name = (string)f.Element("institution");
var x = targetAtt[name].FirstOrDefault(); // just take the first one
if (x != null)
f.Add(new XElement("institution-id", new XAttribute("institution-id-type","fundref"),x.Substring(#"http://dx.doi.org/".Length)));
}
outDoc.Save(file);
}
Console.ReadLine();
But it is not working...Can somebody help...
See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication31
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
const string DATABASE = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List<XElement> prefLabels = rdf.Descendants(nsSkosxl + "prefLabel").ToList();
Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Element(nsSkosxl + "Label").Attribute(nsRdf + "about"))
.ToDictionary(x => x.Key, y => y.ToList());
List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
else
{
Console.WriteLine("Dictionary doesn't contain : '{0}'", institution);
}
}
Console.ReadLine();
}
}
}
I think this is what you are looking for (MODIFIED jdweng's CODE A LITTLE)
const string FILENAME = #"c:\temp\test.xml";
const string DATABASE = #"c:\temp\test1.xml";
public static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsSkos = rdf.GetNamespaceOfPrefix("skos");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List<XElement> prefLabels = rdf.Descendants(nsSkos + "Concept").ToList();
Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Parent.Element(nsSkos+"Concept").Attribute(nsRdf + "about").Value.Substring(18))
.ToDictionary(x => x.Key, y => y.ToList());
List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
}
doc.Save(FILENAME);
Console.WriteLine("Done");
Console.ReadLine();
}

How to read xml file in c# with specific attribute

I have an xml file with attribute
xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"
My C# code:
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
.SelectSingleNode("/BookingCreate/CommitLevel")
.InnerText;
My XML:
<BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
<Authority>
<Org>danco</Org>
<User>xmltest</User>
<Password>xmltest</Password>
<Language>en</Language>
<Currency>EUR</Currency>
<TestDebug>false</TestDebug>
<Version>1.26</Version>
</Authority>
<QuoteId>17081233-3</QuoteId>
<HotelStayDetails>
<Room>
<Guests>
<Adult title="Mr" first="djkvb" last="jkj" />
<Adult title="Mr" first="jfs" last="kjdjs" />
</Guests>
</Room>
</HotelStayDetails>
<HotelSearchCriteria>
<AvailabilityStatus>allocation</AvailabilityStatus>
<DetailLevel>basic</DetailLevel>
</HotelSearchCriteria>
<CommitLevel>prepare</CommitLevel>
</BookingCreate>
What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.
You need to specify the namespace, by using a namespace manager. This should work
XmlDocument bookingXml = new XmlDocument();
bookingXml.Load("PrepareBooking.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(bookingXml.NameTable);
ns.AddNamespace("booking", "http://www.reservwire.com/namespace/WebServices/Xml");
var commitLevel = bookingXml.SelectSingleNode("//booking:BookingCreate//booking:CommitLevel", ns).InnerText;
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 bookingCreate = doc.Descendants().Where(x => x.Name.LocalName == "BookingCreate").FirstOrDefault();
XNamespace ns = bookingCreate.GetDefaultNamespace();
var results = doc.Descendants(ns + "BookingCreate").Select(x => new {
org = (string)x.Descendants(ns + "Org").FirstOrDefault(),
user = (string)x.Descendants(ns + "User").FirstOrDefault(),
password = (string)x.Descendants(ns + "Password").FirstOrDefault(),
language = (string)x.Descendants(ns + "Language").FirstOrDefault(),
currency = (string)x.Descendants(ns + "Currency").FirstOrDefault(),
testDebug = (Boolean)x.Descendants(ns + "TestDebug").FirstOrDefault(),
version = (string)x.Descendants(ns + "Version").FirstOrDefault(),
quoteId = (string)x.Element(ns + "QuoteId"),
guests = x.Descendants(ns + "Adult").Select(y => new {
title = (string)y.Attribute("title"),
first = (string)y.Attribute("first"),
last = (string)y.Attribute("last")
}).ToList(),
availability = (string)x.Descendants(ns + "AvailabilityStatus").FirstOrDefault(),
detailLevel = (string)x.Descendants(ns + "DetailLevel").FirstOrDefault()
}).FirstOrDefault();
}
}
}

Unable to read XML due to parent node

I have the following XML file
<eConnect xmlns:dt="urn:schemas-microsoft-com:datatypes">
<SOPTransactionType>
<eConnectProcessInfo>
<ConnectionString>Data Source=DGLSQL1;Initial Catalog=dgl;Persist Security Info=False;Integrated Security=SSPI</ConnectionString>
<EConnectProcsRunFirst>True</EConnectProcsRunFirst>
</eConnectProcessInfo>
<taSopLotAuto_Items>
<taSopLotAuto>
<SOPTYPE>2</SOPTYPE>
<SOPNUMBE>435462</SOPNUMBE>
<LNITMSEQ>16384</LNITMSEQ>
<ITEMNMBR>7740</ITEMNMBR>
<LOCNCODE>18</LOCNCODE>
<QUANTITY>65</QUANTITY>
<LOTNUMBR>15483D0104X68X</LOTNUMBR>
</taSopLotAuto>
</taSopLotAuto_Items>
</SOPTransactionType>
</eConnect>
I am using the following code to read this file
XmlDocument doc = new XmlDocument();
doc.Load("C:\\SOP.XML");
XmlNodeList nodes = doc.SelectNodes("/taSopLotAuto_Items/taSopLotAutoka");
foreach (XmlNode node in nodes)
{
string text = node["SOPTYPE"].InnerText;
Console.WriteLine(text + "\n");
}
Here I want to read the content of <taSopLoAuto>. But I am unable to read the file content. Is this because of top few lines written in document? Please help me to solve the problem.
The namespace is an issue. You can use Linq like below
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 xml =
"<eConnect xmlns:dt=\"urn:schemas-microsoft-com:datatypes\">" +
"<SOPTransactionType>" +
"<eConnectProcessInfo>" +
"<ConnectionString>Data Source=DGLSQL1;Initial Catalog=dgl;Persist Security Info=False;Integrated Security=SSPI</ConnectionString>" +
"<EConnectProcsRunFirst>True</EConnectProcsRunFirst>" +
"</eConnectProcessInfo>" +
"<taSopLotAuto_Items>" +
"<taSopLotAuto>" +
"<SOPTYPE>2</SOPTYPE>" +
"<SOPNUMBE>435462</SOPNUMBE>" +
"<LNITMSEQ>16384</LNITMSEQ>" +
"<ITEMNMBR>7740</ITEMNMBR>" +
"<LOCNCODE>18</LOCNCODE>" +
"<QUANTITY>65</QUANTITY>" +
"<LOTNUMBR>15483D0104X68X</LOTNUMBR>" +
"</taSopLotAuto>" +
"<taSopLotAuto>" +
"<SOPTYPE>2</SOPTYPE>" +
"<SOPNUMBE>435462</SOPNUMBE>" +
"<LNITMSEQ>16384</LNITMSEQ>" +
"<ITEMNMBR>7740</ITEMNMBR>" +
"<LOCNCODE>18</LOCNCODE>" +
"<QUANTITY>65</QUANTITY>" +
"<LOTNUMBR>15483D0104X68X</LOTNUMBR>" +
"</taSopLotAuto>" +
"<taSopLotAuto>" +
"<SOPTYPE>2</SOPTYPE>" +
"<SOPNUMBE>435462</SOPNUMBE>" +
"<LNITMSEQ>16384</LNITMSEQ>" +
"<ITEMNMBR>7740</ITEMNMBR>" +
"<LOCNCODE>18</LOCNCODE>" +
"<QUANTITY>65</QUANTITY>" +
"<LOTNUMBR>15483D0104X68X</LOTNUMBR>" +
"</taSopLotAuto>" +
"</taSopLotAuto_Items>" +
"</SOPTransactionType>" +
"</eConnect>";
XDocument doc = XDocument.Parse(xml);
List<XElement> taSopLotAutos = doc.Descendants()
.Where(x => x.Name.LocalName == "taSopLotAuto")
.ToList();
var results = taSopLotAutos.Select(x => new
{
sopType = (int)x.Element("SOPTYPE"),
sopNumbe = (int)x.Element("SOPNUMBE"),
lnitmsseg = (int)x.Element("LNITMSEQ"),
locncode = (int)x.Element("LOCNCODE"),
quantity = (int)x.Element("QUANTITY"),
lotnumbr = (string)x.Element("LOTNUMBR")
}).ToList();
}
}
}

Categories