I have the following XML:
<resource>
<description>TTT</description>
<title>TEST</title>
<entity xmlns="TdmBLRuPlUz.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="TdmBLRuPlUz.xsd TdmBLRuPlUz.xsd">
<UzdProd>
<row>
<F_DAUDZ>50</F_DAUDZ>
<BR_DAUDZ/>
<DAUDZ>50</DAUDZ>
<U_DAUDZ/>
<NKODS>ST2.0_014_023</NKODS>
</row>
</UzdProd>
<UzdMat>
<row>
<NKODS>SAG 2.0_014_150</NKODS>
<NNOSAUK>Sagatave 2.0mm*0.14*150m</NNOSAUK>
<PK_VIEN>1</PK_VIEN>
<DAUDZ>0.077</DAUDZ>
<F_DAUDZ>0.077</F_DAUDZ>
</row>
</UzdMat>
</entity>
</resource>
And this is my C# code:
XNamespace ns = "TdmBLRuPlUz.xsd";
XDocument doc = XDocument.Parse(xml);
foreach (XElement element in doc.Descendants(ns + "row"))
{
Console.WriteLine(element.Element(ns + "NKODS").Value);
string NKODS = element.Element(ns + "NKODS").Value;
string F_DAUDZ = element.Element(ns + "F_DAUDZ").Value;
string DAUDZ = element.Element(ns + "DAUDZ").Value;
}
What I need is to read values from the XML nodes NKODS, F_DAUDZ and DAUDZ.
The problem is that there are repeating nodes with those names and with this code it gives me the last ones which are under UzdMat node. What would be the way to get the values for these nodes under UzdProd?
I tried to change row to UzdProd, but that didn't work.
You need to read the specific row you want rather than looping through all of them. For example:
var prodRow = doc.Descendants(ns + "UzdProd").Elements(ns + "row").Single();
var matRow = doc.Descendants(ns + "UzdMat").Elements(ns + "row").Single();
var prodNkods = (string) prodRow.Element(ns + "NKODS");
var matNkods = (string) matRow.Element(ns + "NKODS");
See this fiddle for a working demo.
See if this works :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication25
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement entity = doc.Descendants().Where(x => x.Name.LocalName == "entity").FirstOrDefault();
XNamespace ns = entity.GetDefaultNamespace();
var results = entity.Elements().Select(x => new {
uzd = x.Name.LocalName,
dict = x.Descendants(ns + "row").Elements().GroupBy(y => y.Name.LocalName, z => (string)z)
.ToDictionary(y => y.Key, z => z.FirstOrDefault())
}).ToList();
}
}
}
Related
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");
Okay, so I've been working on reading in a kml file that contains the coordinates of the boundary of every county/city in America. However, I've ran into some problems. Particularly, how to get the value of the NextNode and what to do when there is another element tag in the middle of an element's value.
Here is what the kml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Schema name="gadm36_USA_2" id="gadm36_USA_2">
<SimpleField name="NAME_0" type="string"></SimpleField>
<SimpleField name="NAME_1" type="string"></SimpleField>
<SimpleField name="NAME_2" type="string"></SimpleField>
</Schema>
<Folder><name>gadm36_USA_2</name>
<Placemark>
<Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
<ExtendedData><SchemaData schemaUrl="#gadm36_USA_2">
<SimpleData name="NAME_0">United States</SimpleData>
<SimpleData name="NAME_1">Alabama</SimpleData>
<SimpleData name="NAME_2">Autauga</SimpleData>
</SchemaData></ExtendedData>
<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>-86.8189620971679,32.3402709960939 -86.8108367919922,32.3471298217775 -86.8097915649414,32.3535118103028 -86.8103485107422,32.3585205078126 -86.8158340454101,32.3703498840333 -86.8239974975586,32.3785285949708 -86.8310775756835,32.3839797973634 -86.83544921875,32.3912506103515 -86.8419876098633,32.3980712890626 -86.8452758789062,32.4044418334961 -86.8458633422851,32.4140090942383 -86.8447875976562,32.4167404174805 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>-86.8426208496093,32.4181213378907 -86.8361129760742,32.4204101562501 -86.8296127319336,32.4227104187012 -86.8274383544922,32.4240798950195 -86.8263626098633,32.4259109497071 -86.8280029296875,32.4277305603028 -86.8307189941406,32.4295387268066 </coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
</Placemark>
Note, this is not an actual example where these random element tags appear in the middle of the coordinates, the counties that have them typically have a massive coordinate list and from my experience if i go through the kml file and only use the values before the first element tags, it appears to map out the correct county boundaries
List<string> locationList = new List<string>();
var doc = XDocument.Load("gadm36_USA1.kml");
XNamespace ns = "http://www.opengis.net/kml/2.2";
var result = doc.Root.Descendants(ns + "Placemark");
foreach (XElement xmlInfo in result)
{
var region = xmlInfo.Element(ns + "ExtendedData").Element(ns + "SchemaData").Value;
//var country = region.Element(ns + "SimpleData").Value;
//var state = region.Element(ns + "SimpleData");
//var cityCounty = region.Element(ns + "SimpleData");
locationList = xmlInfo.Element(ns + "MultiGeometry").Value.Split(' ').ToList();
CountyCoordinates.Add(region, locationList);
}
So when i get to the variable "region", it groups all the element values together. For example it will say "United StatesAutaugaAlabama".
As for the coordinates, since there are these random element tags in the middle of the coordinate values, when i split the coordinates by " ", it gets screwed up when it hits these random element tags. (when it gets to that text in the middle of the coordinates the split will return '-86, 32 -86', instead of just '-86, 32') So, I'm essentially looking for help on how to read in the country, state, and county separately and how to properly read in the coordinates despite these random element tags.
I just tested with following a get results :
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 ns = root.GetDefaultNamespace();
List<XElement> simpleFields;
List<XElement> extendedDatas = doc.Descendants(ns + "ExtendedData").ToList();
foreach(XElement extendedData in extendedDatas)
{
simpleFields = extendedData.Descendants(ns + "SimpleData").ToList();
}
}
}
}
I think you meant:
List<XElement> extendedDatas = doc.Descendants(ns + "ExtendedData").ToList();
var a_docment = root.Element(ns + "Document").Value;
var result = doc.Root.Descendants(ns + "Placemark");
foreach (XElement xmlInfo in result)
{
List<string> locationList = new List<string>();
var gg = xmlInfo.Descendants(ns + "outerBoundaryIs").ToList();
foreach (XElement extendedData in gg)
{
locationList.AddRange(extendedData.Value.Split(' ').ToList());
}
I am trying to parse a gml file in C#. That is why I need to select some specific elements on it. What I am trying to do is, selecting coordinates which is located in <lifr:LineString gml:id="ls1">
A part of my gml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:gml ="http://www.opengis.net/gml/3.2" xmlns:lifr="http://www.opengis.net/infragml/road/1.0" xmlns:xlink="http://www.opengis.net/infragml/road/1.0">
<lifr:stringLineSet>
<lifr:StringLineSet gml:id="sls1">
<gml:description>string lines delineating the top pavement surface</gml:description>
<gml:name>top surface pavement</gml:name>
<lifr:stringLineSetID>
<lifr:ID>
<identifier>pavement1</identifier>
</lifr:ID>
</lifr:stringLineSetID>
<lifr:stringLine>
<lifr:StringLine gml:id="sl1">
<gml:description>top surface</gml:description>
<gml:name>left edge pavement</gml:name>
<lifr:stringLineID>
<lifr:ID>
<identifier>LEP</identifier>
</lifr:ID>
</lifr:stringLineID>
<lifr:geometry>
<lifr:LineString gml:id="ls1">
<gml:pos>-3.650 1000 49.927</gml:pos>
<gml:pos>-3.650 1100 48.927</gml:pos>
</lifr:LineString>
</lifr:geometry>
</lifr:StringLine>
</lifr:stringLine>
<lifr:stringLine>
<lifr:StringLine gml:id="sl2">
<gml:description>top surface</gml:description>
<gml:name>centerline pavement</gml:name>
<lifr:stringLineID>
<lifr:ID>
<identifier>CLP</identifier>
</lifr:ID>
</lifr:stringLineID>
<lifr:geometry>
<lifr:LineString gml:id="ls2">
<gml:pos>0.000 1000 50.000</gml:pos>
<gml:pos>0.000 1100 49.000</gml:pos>
</lifr:LineString>
</lifr:geometry>
<lifr:alternativeGeometry xlink:href="ac1"/>
</lifr:StringLine>
</lifr:stringLine>
<lifr:stringLine>
<lifr:StringLine gml:id="sl3">
<gml:description>top surface</gml:description>
<gml:name>right edge pavement</gml:name>
<lifr:stringLineID>
<lifr:ID>
<identifier>REP</identifier>
</lifr:ID>
</lifr:stringLineID>
<lifr:geometry>
<lifr:LineString gml:id="ls3">
<gml:pos>3.650 1000 49.927</gml:pos>
<gml:pos>3.650 1100 48.927</gml:pos>
</lifr:LineString>
</lifr:geometry>
</lifr:StringLine>
</lifr:stringLine>
</lifr:StringLineSet>
</lifr:stringLineSet>
</root>
I tried to write coordinates to console with the code below but I just got blank console.
XNamespace gml = "http://www.opengis.net/gml/3.2";
XNamespace lifr = "http://www.opengis.net/infragml/road/1.0";
XDocument xmlDoc = XDocument.Load(#"C:\Road_example.gml");
IEnumerable<XElement> pavement =
from el in xmlDoc.Elements().Elements(lifr + "LineString")
where (string)el.Attribute(gml + "id") == "ls1"
select xmlDoc.Parent.Element(gml + "pos");
foreach (XElement coords in pavement)
Console.WriteLine(coords);
Console.ReadKey();
Here is solution :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication75
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XNamespace gml = "http://www.opengis.net/gml/3.2";
XNamespace lifr = "http://www.opengis.net/infragml/road/1.0";
XDocument xmlDoc = XDocument.Load(FILENAME);
List<XElement> pavement = xmlDoc.Descendants(lifr + "LineString").ToList();
foreach (XElement coords in pavement)
{
string id = (string)coords.Attribute(gml + "id");
string pos = string.Join(",", coords.Elements(gml + "pos").Select(x => (string)x));
Console.WriteLine("id = '{0}', positions = '{1}'", id, pos);
}
//with filtered results
var ls1 = pavement.Where(x => (string)x.Attribute(gml + "id") == "ls1").FirstOrDefault();
string positions = string.Join(",", ls1.Elements(gml + "pos").Select(x => (string)x));
Console.ReadKey();
}
}
}
I'm new to C#
Here the xml:
<ROOT>
<Columns BaseXPath="//Orders/Position/">
<Colum XPath="#PositionSK" Name="Position"/>
<Colum XPath="#PosGroup" Name="Gruppen-Nr"/>
<Colum XPath="#PosNumber" Name="PositionsNr"/>
<Colum XPath="#PositionCommercialTypeSK" Name="Status"/>
<Colum XPath="#BundlePositionSK" Name="BundlePositionSK"/>
<Colum XPath="#MainPositionSK" Name="MainPositionSK"/>
<Colum XPath="#SalesAgentPrice" Name="Preis"/>
<Colum XPath="#BookingUnitSK" Name="Buch"/>
<Colum XPath="#ContentComponentCommSK" Name="IKO"/>
<Colum XPath="#PositionTypeSK" Name="PositionsTyp"/>
<Colum XPath="//Advertisement[#AdvertisementSK = PositionAdvertisementRelationship/#AdvertisementSK]/#AdvertisementSK" Name="AdvertisementSK"/>
<Colum XPath="//Advertisement[#AdvertisementSK = PositionAdvertisementRelationship/#AdvertisementSK]/#AdvertisementTypeSK" Name="Formatvorgabe"/>
</Columns>
</ROOT>
This xml can always change. So its never the same. Sometimes there are more infos, sometimes less.
This xml give me the certain info, which should be searched in the second "main xml".
So now I know that I have to find the Attribute of PositionSK, PosGroup, PositionCommercialTypeSK, ... . In the other xml.
But how can I do this? The name is never the same, so I need a placeholder for them?
I tried this:
public class ResultNames
{
XmlDocument xml = new XmlDocument();
public List<ResultNames> GetRightNames (string file)
{
xml.Load(file); //this is the xml file
var list = xml.SelectNodes("//ROOT/Columns/Colum");
foreach ( XmlNode colum in list)
{
XmlNode bla = colum.Attributes; //I dont know what I can do here, without any name.
}
return null;
}
and what is with the other xml file, do I need an extra class?
A small sample from the other xml:
<Set>
<Orders OrderSK="0013233309" OrderTypeSK="ORDER" OrderDate="2000-01-01T12:00:00" OrderPrice="0.0000" OrderQuantity="0.00" DistrictSK="0026070180" PaymentTypeSK="E" OrderCreationTypeSK="SNW5ORD" SalesAgentSK="0020025518" ChangeDate="2018-01-25T15:48:29" SalesOrganisationSK="K10-100-1000-50-65" ChangeDateFS="2017-12-11T15:25:21" Source="CORE" Status="C">
<Position PosNumber="3" PosGroup="5" PositionTypeSK="ONL" PositionCommercialTypeSK="DEFAULT"
But its a lot bigger.
Use Xml Linq along with a dictionary
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 FILENAME1 = #"c:\temp\test.xml";
const string FILENAME2 = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME1);
Dictionary<string, XElement> dict = doc.Descendants("Columns").FirstOrDefault().Elements()
.GroupBy(x => (string)x.Attribute("XPath"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
XDocument order = XDocument.Load(FILENAME2);
List<XElement> positions = order.Descendants("Position").ToList();
foreach (XElement position in positions)
{
foreach (XAttribute attribute in position.Attributes())
{
string name = attribute.Name.LocalName;
string value = (string)attribute;
XElement element = dict["#" + name];
element.SetValue(value);
}
}
}
}
}
Code below just gets the Name from first Xml file
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 FILENAME1 = #"c:\temp\test.xml";
const string FILENAME2 = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME1);
Dictionary<string, string> dict = doc.Descendants("Columns").FirstOrDefault().Elements()
.GroupBy(x => (string)x.Attribute("XPath"), y => (string)y.Attribute("Name"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
XDocument order = XDocument.Load(FILENAME2);
List<XElement> positions = order.Descendants("Position").ToList();
foreach (XElement position in positions)
{
foreach (XAttribute attribute in position.Attributes())
{
string name = attribute.Name.LocalName;
string value = (string)attribute;
if(dict.ContainsKey("#" + name))
{
string xName = dict["#" + name];
Console.WriteLine("Key = '{0}', Name = '{1}'", name, xName);
}
else
{
Console.WriteLine("Not in dictionary : Key = '{0}'", name);
}
}
}
}
}
}
I had to make some assumptions about the data you are working with, since you haven't provided examples of everything.
The first assumption is the format of the 2nd XML document. I had to guess from the format of the first document.
The 2nd assumption is that that XPATHs specified in the 1st document Colum elements always point to an Attribute.
void Main()
{
string xml1 =
#"<ROOT>
<Columns BaseXPath=""//Orders/Position/"">
<Colum XPath=""#PositionSK"" Name=""Position""/>
<Colum XPath=""#PosGroup"" Name=""Gruppen-Nr""/>
</Columns>
</ROOT>";
string data =
#"<Set>
<Orders>
<Position PositionSK=""A"" PosGroup=""1"" SomeOtherAttribute=""ABC"" />
<Position PositionSK=""B"" PosGroup=""2"" SomeOtherAttribute=""DEF"" />
</Orders>
</Set>";
var schemaDoc = XDocument.Parse(xml1);
var dataDoc = XDocument.Parse(data);
var itemsXPath = schemaDoc.Descendants("Columns").FirstOrDefault()?.Attribute("BaseXPath").Value;
var basePath = schemaDoc.Descendants("Columns").FirstOrDefault().Attribute("BaseXPath").Value;
// XPATH isn't supposed to end with a trailing "/".
if (basePath.EndsWith("/"))
{
basePath = basePath.Substring(0, basePath.Length - 1);
}
var lines = dataDoc.XPathSelectElements(basePath);
var rowIndex = 0;
foreach (var line in lines)
{
Console.WriteLine($"---Row {rowIndex}");
foreach (var col in schemaDoc.Descendants("Colum"))
{
var columnName = col.Attribute("Name").Value;
Console.Write($"{columnName}: ");
var columnValue = ((XAttribute)((IEnumerable<Object>)line.XPathEvaluate(col.Attribute("XPath").Value)).FirstOrDefault()).Value;
Console.WriteLine(columnValue);
}
Console.WriteLine();
rowIndex++;
}
}
This produces the following output:
---Row 0
Position: A
Gruppen-Nr: 1
---Row 1
Position: B
Gruppen-Nr: 2
You can change the attributes that are output by adjusting the content of xml1.
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();
}
}
}