How to i loop the Xelement class and get the below result - c#

Using a loop with xelement class in C# i would like to get the below result!
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>
This is the code i have tried so far! any help?? i need to use a loop and get the above values..The loop i used is commented..
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
XElement xmlDataStore = new XElement("data",
new XElement("cities",
new XElement("city", new XAttribute("id", "1")),
new XElement("city", "Colombo"),
new XElement("name", "lname"),
new XElement("state", "0772569984")
)
)
;
//var list = from x in XElement.ReadFrom(xmlDataStore).Element("Node").Elements()
//select new
//{
// Name = x.Name,
// Value = (string)x
//};
Console.WriteLine(xmlDataStore);
Console.ReadLine();
}
}
}
What i get...
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
</cities>
What i want...
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>

Okay, I still don't exactly know what the real problem is, so let's start with this:
private static void citiesXml()
{
const string desc = "Cities that I have recently visited.";
// set up a list of all the different cities
var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("Chicago1", "IN1"));
list.Add(new Tuple<string, string>("Chicago2", "IN2"));
list.Add(new Tuple<string, string>("Chicago3", "IN3"));
var xmlDataStore = new XElement("data", new XElement("description", desc));
var xmlCities = new XElement("cities");
// loop through the list of cities and create a XElement for each single one
for (var i = 0; i < list.Count; i++)
{
xmlCities.Add(new XElement("city",
new XAttribute("id", i + 1),
new XElement("name", list[i].Item1),
new XElement("state", list[i].Item2)));
}
// add the cities to the data store object
xmlDataStore.Add(xmlCities);
Console.WriteLine(xmlDataStore);
Console.ReadLine();
}
This will print:
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>
So as far as I see it, the only difference is that there are no blank lines between cities. Are the missing blank lines the problem?

Check by Descendants
XDocument xdoc = XDocument.Load("Xml File Path"); //save that xml in "C:\test.xml "
IEnumerable<XElement> xEle = xdoc.XPathSelectElements("//cities");
if(xEle !=null)
{
foreach(XElement xE in Xelement.Descendants())
{
// here you will get everything ......
}
}
you can loop through

Related

c# Merging two XMLs giving error

I am trying to merge two XMLs with same structure but different data into one.
I am getting this error: A node of type Document cannot be added to content.
Below is my code
var productElements =
testGroupProvider.GetTestGroup().ProductTests.Select(
productTest => new XElement(xNamespace + "Product",
new XElement(xNamespace + "ExternalId", productTest.ProductNameKey),
new XElement(xNamespace + "Name", testGroupProvider.GetProductName(productTest)),
new XElement(xNamespace + "ImageUrl", ChoiceBaseHostName + GetProductImageUrl(productTest, TargetDatabase))));
var root = new XDocument(
new XElement(xNamespace + "Feed",
new XAttribute("xmlns", xNamespace),
new XAttribute("name", BVFeedsName),
new XAttribute("incremental", "true"),
new XAttribute("extractDate", DateTime.Now.ToString("o")),
new XElement(xNamespace + "Categories",
new XElement(xNamespace + "Category",
new XElement(xNamespace + "ExternalId", testGroupProvider.GetProductGroup().Id),
new XElement(xNamespace + "Name", testGroupProvider.GetProductGroup().Name),
testGroupProvider.GetTestGroup().Name),
new XElement(xNamespace + "Products", productElements)));
var filePath = #"D:\testXML\test.xml";
XElement xml = XElement.Load(filePath);
xml.Add(root);
xml.Save(filePath);
Can anyone tell me what i am doing wrong.
This is the XML structure in test.xml
<?xml version="1.0" encoding="utf-8"?>
<Feed xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6" name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00">
<Categories>
<Category>
<ExternalId>{09B3B4FB-F5CF-4522-BE96-4C4B535580C3}</ExternalId>
<Name>Cereal and muesli</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>coles-almond-hazelnut-macadamia-cluster-fusions</ExternalId>
<Name>Coles Almond, Hazelnut & Macadamia Cluster Fusions</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
The second XML has the same structure with different products
<?xml version="1.0" encoding="utf-8"?>
<Feed xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6" name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00">
<Categories>
<Category>
<ExternalId>{12}</ExternalId>
<Name>cat1</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>Id</ExternalId>
<Name>Ccoles</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
I want to combine them like below
<?xml version="1.0" encoding="utf-8"?>
<Feed xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6" name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00">
<Categories>
<Category>
<ExternalId>{09B3B4FB-F5CF-4522-BE96-4C4B535580C3}</ExternalId>
<Name>Cereal and muesli</Name>
</Category>
<Category>
<ExternalId>{12}</ExternalId>
<Name>cat1</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>coles-almond-hazelnut-macadamia-cluster-fusions</ExternalId>
<Name>Coles Almond, Hazelnut & Macadamia Cluster Fusions</Name>
<ImageUrl></ImageUrl>
</Product>
<Product>
<ExternalId>Id</ExternalId>
<Name>Ccoles</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
A xml document must have only one root.
Working with the documents you attached, you can replace the xml.Add(root); with the following (i.e. it will add each node under one root to the other xml root)
foreach (var child in root.Root.Elements())
{
xml.Element(child.Name.ToString()).Add(child.Nodes());
}
Edit - A further generalization
You can generalize the above code using a Merge extension of 2 XElements so that it reads as follows
foreach (var child in root.Elements())
{
xml.Element(child.Name.ToString()).Merge(child, xNamespace + "ExternalId");
}
Having defined the extension
public static void Merge(this XElement root1, XElement root2, XName element_id)
{
root1.Add(root2.Elements().Except(root1.Elements(), new MyComparer(element_id)));
}
with a xml comparer
public class MyComparer : IEqualityComparer<XElement>
{
private XName _element_id;
public MyComparer(XName element_id)
{
_element_id = element_id;
}
public bool Equals(XElement x, XElement y)
{
return x.Element(_element_id).Value.Equals(y.Element(_element_id).Value);
}
public int GetHashCode(XElement el)
{
return el.Element(_element_id).Value.GetHashCode();
}
}
Select correct nodes to add and correct nodes to be added.
var filePath = #"D:\testXML\test.xml";
XElement xml = XElement.Load(filePath);
var xmlCategories = xml.Descendants("Categories").First();
var rootCategories = root.Descendants("Category");
xmlCategories.Add(rootCategories);
var xmlProducts = xml.Descendants("Products").First();
var rootProducts = root.Descendants("Product");
xmlProducts.Add(rootProducts);
xml.Save(filePath);
Be crystal clear what you are doing.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME1 = #"c:\temp\test1.xml";
const string FILENAME2 = #"c:\temp\test2.xml";
static void Main(string[] args)
{
XDocument doc1 = XDocument.Load(FILENAME1);
XDocument doc2 = XDocument.Load(FILENAME2);
XElement category1 = doc1.Descendants().Where(x => x.Name.LocalName == "Categories").FirstOrDefault();
XElement category2 = doc2.Descendants().Where(x => x.Name.LocalName == "Categories").FirstOrDefault();
category1.Add(category2.Descendants());
XElement product1 = doc1.Descendants().Where(x => x.Name.LocalName == "Products").FirstOrDefault();
XElement product2 = doc2.Descendants().Where(x => x.Name.LocalName == "Products").FirstOrDefault();
product1.Add(product2.Descendants());
}
}
}
Try this, sorry about the VB
'second is The second XML has the same structure with different products
Dim combined As XElement = New XElement(test) 'create copy of test.xml
combined.<Categories>.LastOrDefault.Add(second.<Categories>.Elements)
combined.<Products>.LastOrDefault.Add(second.<Products>.Elements)
or
'if test can be used to combine then
test.<Categories>.LastOrDefault.Add(second.<Categories>.Elements)
test.<Products>.LastOrDefault.Add(second.<Products>.Elements)
The result is
<Feed name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00" xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6">
<Categories>
<Category>
<ExternalId>{09B3B4FB-F5CF-4522-BE96-4C4B535580C3}</ExternalId>
<Name>Cereal and muesli</Name>
</Category>
<Category>
<ExternalId>{12}</ExternalId>
<Name>cat1</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>coles-almond-hazelnut-macadamia-cluster-fusions</ExternalId>
<Name>Coles Almond, Hazelnut & Macadamia Cluster Fusions</Name>
<ImageUrl></ImageUrl>
</Product>
<Product>
<ExternalId>Id</ExternalId>
<Name>Ccoles</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
The test data I used is
Dim test As XElement =
<Feed xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6" name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00">
<Categories>
<Category>
<ExternalId>{09B3B4FB-F5CF-4522-BE96-4C4B535580C3}</ExternalId>
<Name>Cereal and muesli</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>coles-almond-hazelnut-macadamia-cluster-fusions</ExternalId>
<Name>Coles Almond, Hazelnut & Macadamia Cluster Fusions</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
Dim second As XElement =
<Feed xmlns="http://www.bazaarvoice.com/xs/PRR/ProductFeed/5.6" name="Choice" incremental="true" extractDate="2016-07-12T15:24:44.5732750+10:00">
<Categories>
<Category>
<ExternalId>{12}</ExternalId>
<Name>cat1</Name>
</Category>
</Categories>
<Products>
<Product>
<ExternalId>Id</ExternalId>
<Name>Ccoles</Name>
<ImageUrl></ImageUrl>
</Product>
</Products>
</Feed>
The XElements can be loaded like this
test = XElement.Load("PATH")
second = XElement.Load("second PATH")
and saved like this
test.Save("PATH")
second.Save("second PATH")
combined.Save("combined PATH")

Descendants not found even if they exist in XDocument in C#

I am having problems with getting descendant with specific name. I have hugh XML that basically is made of lots of this elements:
<?xml version="1.0" encoding="utf-8"?>
<Search_Results xmlns="https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd">
<Entity Record="28" ResultID="12460985">
<GeneralInfo>
<EntityType>Individual</EntityType>
<Name>Jón Jónsson</Name>
<DOB>01/01/0001</DOB>
<DOBParsed />
<AccountID>ABS-ASSOC-10-109</AccountID>
<IDLabel>Account ID</IDLabel>
<IDNumber>ABS-ASSOC-10-109</IDNumber>
<AddressType>Current</AddressType>
<PostalCode>Somalia</PostalCode>
</GeneralInfo>
<RecordDetailInfo>
<EntityType>Individual</EntityType>
<SearchDate>2016-05-13 09:53:50Z</SearchDate>
<Origin>Automatic Batch</Origin>
<FirstName>Jón</FirstName>
<LastName>Jónsson</LastName>
<FullName>Jón Jónsson</FullName>
<AdditionalInfo>
<Type>Date of Birth</Type>
<Information>01/01/0001</Information>
</AdditionalInfo>
<Addresses>
<Type>Current</Type>
<PostalCode>Somalia</PostalCode>
</Addresses>
<Identifications>
<Type>Account ID</Type>
<Number>ABS10-109</Number>
</Identifications>
</RecordDetailInfo>
<WatchList>
<Match ID="1">
<EntityName>Jonsson</EntityName>
<EntityScore>96</EntityScore>
<BestName>Jonsson, Jon Orn</BestName>
<BestNameScore>96</BestNameScore>
<FileName>WorldCompliance - Full.BDF</FileName>
<SourceDate>2016-05-11 05:01:00Z</SourceDate>
<DistributionDate>2016-05-12 14:59:39Z</DistributionDate>
<ResultDate>2016-05-13 09:53:50Z</ResultDate>
<EntityUniqueID>WX0003219444</EntityUniqueID>
<MatchDetails>
<Entity Type="2">
<Number>3219444</Number>
<Date>9/3/2012</Date>
<Reason>International</Reason>
<CheckSum>69185</CheckSum>
<Gender>Male</Gender>
<Name>
<First>Jon Orn</First>
<Last>Jonsson</Last>
<Full>Jon Orn Jonsson</Full>
</Name>
<Notes>Source.</Notes>
<Addresses>
<Address ID="1" Type="4">
<Country>Iceland</Country>
</Address>
</Addresses>
<IDs>
<ID ID="1" Type="27">
<Number>3219444</Number>
</ID>
</IDs>
<Descriptions>
<Description ID="1" Type="10">
<Value>Honorary Consul of Iceland in Saskatchewan, Canada</Value>
<Notes>Starting 2002 Ending 2014</Notes>
</Description>
<Description ID="2" Type="22">
<Value>Link to WorldCompliance Online Database</Value>
<Notes>Jonsson, Jon Orn | https://members.worldcompliance.com/metawatch2.aspx?id=e0399c29-7c5e-4674-874c-f36fdb19052e</Notes>
</Description>
<Description ID="3" Type="22">
<Value>Sources of Record Information</Value>
<Notes>http://brunnur.mfa.is/interpro/utanr/HBvefur.nsf/Pages/IslSendiradIsl?OpenDocument&amp | CountryNr=1(Canada)&amp | Lang=44') | http://www.international.gc.ca/protocol-protocole/assets/pdfs/Diplomatic_List.pdf | http://www.inlofna.org/Elfros/newsletter%20January%202010.pdf | http://publications.gc.ca/collections/Collection/E12-3-2002E.pdf | http://www.onlygolfnews.com/golf-canada-saskatchewan/saskatchewan-golf-first-fort-lacrosse-ted-brandon-over-new-last-snow.htm | http://www.ops.gov.sk.ca/Consular-Officers</Notes>
</Description>
</Descriptions>
</Entity>
</MatchDetails>
</Match>
</WatchList>
</Entity>
</Search_Results>
I am trying to reach all elements with name: Entity and later I want to go through all of them and get values from their descendants with name "Reason".
But non of the Entity elements is found with this line:
var entityList = xmlDoc.Descendants(nameSpace + "Entity").ToList();
This is a whole method I am using:
public static void GetIBANAndBicValuesFromXML(XDocument xmlDoc)
{
var reasons = new List<string>();
XNamespace nameSpace =
"https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/";
var entityList = xmlDoc.Descendants(nameSpace + "Entity").ToList();
if (entityList != null)
{
foreach (var reason in entityList.Select(entity => entity.Elements(nameSpace + "Reason"))
.Where(reasonsList => reasonsList != null).SelectMany(reasonsList => reasonsList))
{
string reasonValue = reason.Value;
reasons.Add(reasonValue);
}
}
}
And this is a call to this method:
private static void Main(string[] args)
{
var xmlFile = "C:\\temp\\indi2.xml";
var x = XDocument.Load("C:\\temp\\Individuals.xml");
XMLParse.GetIBANAndBicValuesFromXML(x);
}
I have tried namespace like this as well:
"https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd"
But no success.
Anybody sees what I am doing wrongly?
You can use Linq to filter with LocalName:
string fileName = "1.txt";
var xDoc = XDocument.Load(fileName);
var neededElements = xDoc.Descendants().Where(x => x.Name.LocalName == "Entity");
Console.WriteLine("Found {0} Entitys", neededElements.Count());
foreach(var el in neededElements)
{
Console.WriteLine(el);
}

Merge parent nodes if child nodes identical xml

Let me put the scenario:
If the 'Student' node has same child elements then merge the 'Student' node. In this case if the 'Name' node is found in other 'Student' nodes with same value then those 2 'Student' nodes need to be merged with unique elements. In this case the 'Name' node being identical comes 1 time and the 'Address' node coming 2 times.
Also the input xml can have different set of child nodes and can have different names every time.
Below is Input xml
<Root>
<Student>
<Name>Tim</Name>
<Address>
<City>
<Location1>MEL</Location1>
</City>
</Address>
</Student>
<Student>
<Name>Tim</Name>
<Address>
<City>
<Location1>DEL</Location1>
</City>
</Address>
</Student>
<Student>
<Name>1</Name>
<FatherName>Papa</FatherName>
<Address>
<Suburb>1</Suburb>
<City>
<Location1>HNL</Location1>
</City>
</Address>
</Student>
<Student>
<Name>1</Name>
<MotherName>Mom</MotherName>
<Address>
<City>
<Location1>HNL</Location1>
</City>
</Address>
</Student>
</Root>
Expected xml:
<Root>
<Student>
<Name>Tim</Name>
<Address>
<City>
<Location1>MEL</Location1>
</City>
</Address>
<Address>
<City>
<Location1>DEL</Location1>
</City>
</Address>
</Student>
<Student>
<Name>1</Name>
<FatherName>Papa</FatherName>
<Address>
<Suburb>1</Suburb>
<City>
<Location1>HNL</Location1>
</City>
</Address>
</Student>
<Student>
<Name>1</Name>
<MotherName>Mom</MotherName>
<Address>
<City>
<Location1>HNL</Location1>
</City>
</Address>
</Student>
</Root>
I tried to implement with the below code. I know its not very efficient.
var newdoc = XDocument.Parse(input);
// 'restriction' is the concerned node
foreach (var element in newdoc.Descendants("restriction"))
{
if (skiptimes > 0)
{
skiptimes--;
continue;
}
//Get distinct node names for 'element'
var distinctNodeName = element.Elements().Select(cc => cc.Name).Distinct();
//delete if found 'freetext' node as the this do not need to be comapared
distinctNodeName = distinctNodeName.Where(n => n.LocalName.ToString() != "FreeText");
//Get distinct elements
var distinctElementName = element.Elements().Select(xx => xx).Distinct();
foreach (var nextelement in element.ElementsAfterSelf())
{
if (!nextelement.IsEmpty)
{
//Get distinct node names for 'nextelement'
var distinctNodeName2 = nextelement.Elements().Select(xx => xx.Name).Distinct();
//delete if found 'freetext' node as the this do not need to be comapared
distinctNodeName2 = distinctNodeName2.Where(n => n.LocalName.ToString() != "FreeText");
//Get distinct elements
var distinctElements2 = nextelement.Elements().Select(xx => xx).Distinct();
//From 'element' excluding the 'StopoverSegs' node which by default always come as last node
var subelements = element.Elements().Take(distinctNodeName.Count() - 1);
//From 'nextelement' excluding the 'StopoverSegs' node which by default always come as last node
var sub2 = nextelement.Elements().Take(distinctNodeName2.Count() - 1);
// Compare node name counts which are selected as distinct
if (distinctNodeName.Count() == distinctNodeName2.Count())
{
ArrayList fir = new ArrayList();
int arrcount = 0; ArrayList sec = new ArrayList();
//Add 'element' to array list for comparison
foreach (var firstSet in subelements)
{
fir.Add(firstSet.ToString()); arrcount++;
}
//Add 'nextelement' to array list for comparison
foreach (var secondSet in sub2)
{
sec.Add(secondSet.ToString());
}
//comparison . I could not get through to compare via SequenceEqual or other custom
//extension
for (int i = 0; i < arrcount; i++)
{
if (fir[i].ToString().Trim() != sec[i].ToString().Trim())
{
GotEqual = false;
break;
}
else
{
GotEqual = true;
}
}
if (GotEqual)
{
element.Add(nextelement.Elements().Except(element.Elements(), new ElementComparer()));
skiptimes++;
}
else
{
break;
}
}
}
}
finalXML.Add(element);
}
This is horrible code, and I haven't had time to clean it up, but this works.
var xDoc = XDocument.Parse("<and><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>4</NbMaxOfStops><Charges1><FirstAmount Currency=\"AUD\">10.00</FirstAmount></Charges1><StopoversSegs><GeoSpec><Location1>AKL</Location1><Location2>CHC</Location2></GeoSpec><ChargeIndicator>1</ChargeIndicator></StopoversSegs><StopoversSegs><GeoSpec><Location1>LAX</Location1><Location2>RAR</Location2></GeoSpec><ChargeIndicator>1</ChargeIndicator></StopoversSegs></restriction><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>2</NbMaxOfStops><NbOfOutboundStops>1</NbOfOutboundStops><NbOfInboundStops>1</NbOfInboundStops><Charges1><FirstAmountNbOf>1</FirstAmountNbOf><FirstAmount Currency=\"AUD\">301.00</FirstAmount><AdditionalAmountNbOf>1</AdditionalAmountNbOf><AdditionalAmount Currency=\"AUD\">151.00</AdditionalAmount></Charges1><StopoversSegs><NbOfStops>1</NbOfStops><GeoSpec><Location1>LAX</Location1></GeoSpec><InboundOutboundIndicator>I</InboundOutboundIndicator><ChargeIndicator>1</ChargeIndicator></StopoversSegs></restriction><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>2</NbMaxOfStops><NbOfOutboundStops>1</NbOfOutboundStops><NbOfInboundStops>1</NbOfInboundStops><Charges1><FirstAmountNbOf>1</FirstAmountNbOf><FirstAmount Currency=\"AUD\">301.00</FirstAmount><AdditionalAmountNbOf>1</AdditionalAmountNbOf><AdditionalAmount Currency=\"AUD\">151.00</AdditionalAmount></Charges1><StopoversSegs><NbOfStops>1</NbOfStops><GeoSpec><Location1>SFO</Location1></GeoSpec><InboundOutboundIndicator>O</InboundOutboundIndicator><ChargeIndicator>2</ChargeIndicator></StopoversSegs></restriction></and>");
var xDoc2 = XDocument.Parse("<and><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>4</NbMaxOfStops><Charges1><FirstAmount Currency=\"AUD\">10.00</FirstAmount></Charges1><StopoversSegs><GeoSpec><Location1>AKL</Location1><Location2>CHC</Location2></GeoSpec><ChargeIndicator>1</ChargeIndicator></StopoversSegs><StopoversSegs><GeoSpec><Location1>LAX</Location1><Location2>RAR</Location2></GeoSpec><ChargeIndicator>1</ChargeIndicator></StopoversSegs></restriction><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>2</NbMaxOfStops><NbOfOutboundStops>1</NbOfOutboundStops><NbOfInboundStops>1</NbOfInboundStops><Charges1><FirstAmountNbOf>1</FirstAmountNbOf><FirstAmount Currency=\"AUD\">301.00</FirstAmount><AdditionalAmountNbOf>1</AdditionalAmountNbOf><AdditionalAmount Currency=\"AUD\">151.00</AdditionalAmount></Charges1><StopoversSegs><NbOfStops>1</NbOfStops><GeoSpec><Location1>LAX</Location1></GeoSpec><InboundOutboundIndicator>I</InboundOutboundIndicator><ChargeIndicator>1</ChargeIndicator></StopoversSegs></restriction><restriction type=\"Stopovers_Type\" Name=\"STP\"><NbMaxOfStops>2</NbMaxOfStops><NbOfOutboundStops>1</NbOfOutboundStops><NbOfInboundStops>1</NbOfInboundStops><Charges1><FirstAmountNbOf>1</FirstAmountNbOf><FirstAmount Currency=\"AUD\">301.00</FirstAmount><AdditionalAmountNbOf>1</AdditionalAmountNbOf><AdditionalAmount Currency=\"AUD\">151.00</AdditionalAmount></Charges1><StopoversSegs><NbOfStops>1</NbOfStops><GeoSpec><Location1>SFO</Location1></GeoSpec><InboundOutboundIndicator>O</InboundOutboundIndicator><ChargeIndicator>2</ChargeIndicator></StopoversSegs></restriction></and>");
xDoc.Root.Descendants().Where(w => w.Name == "StopoversSegs").Remove();
var lsDistinct = xDoc.Root.Elements().Select(s => s.ToString()).Distinct().ToList();
var lDistinct = lsDistinct.Select(s => Tuple.Create(s, XElement.Parse(s))).ToList();
var lStopNodes = xDoc2.Root.Elements().Select(s => Tuple.Create(XElement.Parse(s.ToString()), XElement.Parse(s.ToString()))).ToList();
foreach ( var stopNode in lStopNodes)
{
stopNode.Item1.Descendants("StopoversSegs").Remove();
}
var lStopNodesToDistinct = lStopNodes.Select(s => Tuple.Create(s.Item1.ToString(), s.Item2.Descendants("StopoversSegs"))).ToList();
foreach (var distinct in lDistinct)
{
distinct.Item2.Add(lStopNodesToDistinct.Where(w => w.Item1 == distinct.Item1).Select(s => s.Item2.Nodes()).ToArray());
var test = lStopNodesToDistinct.Where(w => w.Item1 == distinct.Item1).Select(s => s.Item2.Nodes()).ToArray();
}
xDoc.Root.Elements().Remove();
xDoc.Root.Add(lDistinct.Select(s => s.Item2));

generate XML with nested parameter in c#.net

I want to generate an XML with parameter by parsing the following xml. i am working in c#.net.
<root>
<name1>
<names>
<id>5</id>
<class>space</class>
<from>Germany</from>
<to>France</to>
<through>
<via>
<id>4</id>
<route>Zurich<route>
</via>
<via>
<id>7</id>
<route>Vienna<route>
</via>
</through>
</names>
</name1>
<name2>
<newNames>
<id>8</id>
<path>Road</path>
<dest>USA</dest>
<through>
<route1>
<id>5</id>
<naviagte>Britain</naviagte>
</route1>
<route1>
<id>2</id>
<naviagte>Canada</naviagte>
</route1>
</through>
</newNames>
</name2>
</root>
i want to convert it like following-
<root>
<name1>
<names id = "5";class = "space"; from = "Germany" ; to = "France">
<through>
<via id = "4" ; route = "Zurich">
<via id = "7" ; route = "Vienna">
</through>
</names>
</name1>
<name2>
<newNames id = "8"; path = "Road"; dest = "USA">
<newNames id = "8"; path = "Road"; dest = "USA">
<through>
<route1 = id = "5" ; naviagte = "Britain">
<route1 = id = "2" ; naviagte = "Canada">
</through>
</name2>
</root>
i have tried the following codes.
var doc = XDocument.Load("xml_file.xml");
Console.WriteLine(doc.ToString());
var names = doc.Descendants("name");
var newRootElement = new XElement("root");
foreach (var name in names)
{
var newNameElement = new XElement(name.Name);
foreach (var element in name.Elements())
{
newNameElement.SetAttributeValue(element.Name, element.Value);
}
newRootElement.Add(newNameElement);
}
Console.WriteLine(newRootElement.ToString());
newRootElement.Save("converted_xml_file.xml");
but i can't parse all the nodes. could anyone give me any hints or correction in my codes please ?
I suppose you have closed route tags in your input xml. If so, then you can build new xml by querying original xml and replacing elements with attributes:
var xdoc = XDocument.Load("xml_file.xml");
var root =
new XElement("root",
from name in xdoc.Root.Elements()
select new XElement(name.Name,
from names in name.Elements()
select new XElement(names.Name,
from namesElement in names.Elements()
where namesElement.Name.LocalName != "through"
select new XAttribute(namesElement.Name.LocalName, (string)namesElement),
new XElement("through",
from route in names.Element("through").Elements()
select new XElement(route.Name,
from routeElement in route.Elements()
select new XAttribute(routeElement.Name.LocalName, (string)routeElement))))));
This code produces following xml:
<root>
<name1>
<names id="5" class="space" from="Germany" to="France">
<through>
<via id="4" route="Zurich" />
<via id="7" route="Vienna" />
</through>
</names>
</name1>
<name2>
<newNames id="8" path="Road" dest="USA">
<through>
<route1 id="5" naviagte="Britain" />
<route1 id="2" naviagte="Canada" />
</through>
</newNames>
</name2>
</root>

Xml simplification/extraction of distinct values - possible LINQ

Sorry for this long post....But i have a headache from this task.
I have a mile long xml document where I need to extract a list, use distinct values, and pass for transformation to web.
I have completed the task using xslt and keys, but the effort is forcing the server to its knees.
Description:
hundreds of products in xml, all with a number of named and Id'ed cattegories, all categories with at least one subcategory with name and id.
The categories are unique with ID, all subcategories are unique WITHIN that category:
Simplified example form the huge file (left our tons of info irrelevant to the task):
<?xml version="1.0" encoding="utf-8"?>
<root>
<productlist>
<product id="1">
<name>Some Product</name>
<categorylist>
<category id="1">
<name>cat1</name>
<subcategories>
<subcat id="1">
<name>subcat1</name>
</subcat>
<subcat id="2">
<name>subcat1</name>
</subcat>
</subcategories>
</category>
<category id="2">
<name>cat1</name>
<subcategories>
<subcat id="1">
<name>subcat1</name>
</subcat>
</subcategories>
</category>
<category id="3">
<name>cat1</name>
<subcategories>
<subcat id="1">
<name>subcat1</name>
</subcat>
</subcategories>
</category>
</categorylist>
</product>
<product id="2">
<name>Some Product</name>
<categorylist>
<category id="1">
<name>cat1</name>
<subcategories>
<subcat id="2">
<name>subcat2</name>
</subcat>
<subcat id="4">
<name>subcat4</name>
</subcat>
</subcategories>
</category>
<category id="2">
<name>cat2</name>
<subcategories>
<subcat id="1">
<name>subcat1</name>
</subcat>
</subcategories>
</category>
<category id="3">
<name>cat3</name>
<subcategories>
<subcat id="1">
<name>subcat1</name>
</subcat>
</subcategories>
</category>
</categorylist>
</product>
</productlist>
</root>
DESIRED RESULT:
<?xml version="1.0" encoding="utf-8"?>
<root>
<maincat id="1">
<name>cat1</name>
<subcat id="1"><name>subcat1</name></subcat>
<subcat id="2"><name>subcat2</name></subcat>
<subcat id="3"><name>subcat3</name></subcat>
</maincat>
<maincat id="2">
<name>cat2</name>
<subcat id="1"><name>differentsubcat1</name></subcat>
<subcat id="2"><name>differentsubcat2</name></subcat>
<subcat id="3"><name>differentsubcat3</name></subcat>
</maincat>
<maincat id="2">
<name>cat2</name>
<subcat id="1"><name>differentsubcat1</name></subcat>
<subcat id="2"><name>differentsubcat2</name></subcat>
<subcat id="3"><name>differentsubcat3</name></subcat>
</maincat>
</root>
(original will from 2000 products produce 10 categories with from 5 to 15 subcategories)
Things tried:
Xslt with keys - works fine, but pooooor performance
Played around with linq:
IEnumerable<XElement> mainCats =
from Category1 in doc.Descendants("product").Descendants("category") select Category1;
var cDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("root"));
cDoc.Root.Add(mainCats);
cachedCategoryDoc = cDoc.ToString();
Result was a "categories only" (not distinct values of categories or subcategories)
Applied the same xlst to that, and got fairly better performance..... but still far from usable...
Can i apply some sort of magic with the linq statement to have the desired output??
A truckload of good karma goes out to the ones that can point me in det right direction..
//Steen
NOTE:
I am not stuck on using linq/XDocument if anyone has better options
Currently on .net 3.5, can switch to 4 if needed
If I understood your question corectly, here's a LINQ atempt.
The query below parses your XML data and creates a custom type which represents a category and contains the subcategories of that element.
After parsing, the data is grouped by category Id to get distinct subcategories for each category.
var doc = XElement.Load("path to the file");
var results = doc.Descendants("category")
.Select(cat => new
{
Id = cat.Attribute("id").Value,
Name = cat.Descendants("name").First().Value,
Subcategories = cat.Descendants("subcat")
.Select(subcat => new
{
Id = subcat.Attribute("id").Value,
Name = subcat.Descendants("name").First().Value
})
})
.GroupBy(x=>x.Id)
.Select(g=>new
{
Id = g.Key,
Name = g.First().Name,
Subcategories = g.SelectMany(x=>x.Subcategories).Distinct()
});
From the results above you can create your document using the code below:
var cdoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("root"));
cdoc.Root.Add(
results.Select(x=>
{
var element = new XElement("maincat", new XAttribute("id", x.Id));
element.Add(new XElement("name", x.Name));
element.Add(x.Subcategories.Select(c=>
{
var subcat = new XElement("subcat", new XAttribute("id", c.Id));
subcat.Add(new XElement("name", c.Name));
return subcat;
}).ToArray());
return element;
}));
Try this i have done something for it.. attributes are missing you can add them using XElement ctor
var doc = XDocument.Load(reader);
IEnumerable<XElement> mainCats =
doc.Descendants("product").Descendants("category").Select(r =>
new XElement("maincat", new XElement("name", r.Element("name").Value),
r.Descendants("subcat").Select(s => new XElement("subcat", new XElement("name", s.Element("name").Value)))));
var cDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("root"));
cDoc.Root.Add(mainCats);
var cachedCategoryDoc = cDoc.ToString();
Regards.
This will parse your xml into a dictionary of categories with all the distinct subcategory names. It uses XPath from this library: https://github.com/ChuckSavage/XmlLib/
XElement root = XElement.Load(file);
string[] cats = root.XGet("//category/name", string.Empty).Distinct().ToArray();
Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
foreach (string cat in cats)
{
// Get all the categories by name and their subcat names
string[] subs = root
.XGet("//category[name={0}]/subcategories/subcat/name", string.Empty, cat)
.Distinct().ToArray();
dict.Add(cat, subs);
}
Or the parsing as one statement:
Dictionary<string, string[]> dict = root
.XGet("//category/name", string.Empty)
.Distinct()
.ToDictionary(cat => cat, cat => root
.XGet("//category[name={0}]/subcategories/subcat/name", string.Empty, cat)
.Distinct().ToArray());
I give you the task of assembling your resulting xml from the dictionary.

Categories