insert new node with its attribute to xml - c#

I have the following xml node
<group>
<level id="1" name="Level 1" />
<level id="2" name="Level 2" />
</group>
How can insert new element with it's attributes to xml file

var doc = XDocument.Load("yourxmlfile.xml");
var x = new XElement("level",
new XAttribute("id", 3),
new XAttribute("name", "Level 3"));
doc.Element("group").Add(x);
doc.Save("yourxmlfile.xml");

Related

convert list to xml in c#

I have a list of string. I need to convert it into an xml document. Am using XElement to achieve this.
List<string> list= myString.Split(',').ToList();
XElement xmlElements = new XElement("Root", new XElement("Number",list.Select(i => new XElement("Num", i))));
System.Console.Write(xmlElements);
System.Console.Read();
I get the below format.
<Root>
<Number>
<Num></Num>
<Num></Num>
</Number>
</Root>
But I need something like this.
<Root>
<Number id=1>
<Num></Num>
</Number>
<Number id=2>
<Num></Num>
</Number>
</Root>
How to achieve this.
If by an id you mean an index, then:
XElement xmlElements =
new XElement("Root",
list.Select((i, index) => new XElement("Number",
new XAttribute("id", index),
new XElement("Num", i))));
The result for the "a,b,c" will be
<Root>
<Number id="0">
<Num>a</Num>
</Number>
<Number id="1">
<Num>b</Num>
</Number>
<Number id="2">
<Num>c</Num>
</Number>
</Root>

Get XML attribute Values by its Descendants

I have an XML in this Format and I want to get List of Line ID and its Name
<ArrayOfLines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<LineStatus ID="0" StatusDetails="">
<BranchDisruptions />
<Line ID="1" Name="Line1" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
<LineStatus ID="1" StatusDetails="">
<BranchDisruptions />
<Line ID="2" Name="Line2" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
</ArrayOfLines>
and This is the code I have written:
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = from c in xmlFile.Descendants("LineStatus") select c;
but it is not returning me any results.
Here is my idea but you have to create list "namesList" and "idList" before. Try this:
XDocument xDoc = XDocument.Load("your xml file");
foreach (var elem in xDoc.Document.Descendants("line"))
{
idList.Add(elem.Attribute("ID").Value);
namesList.Add(elem.Attribute("Name").Value);
}
And you have full controll by index of each list to this data. After that you can also create object of these 2 elements
You have an xml namespace, you need to specify it with element names:
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var query = from c in xmlFile.Descendants(ns + "LineStatus") select c;
Try this...
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = (from c in xmlFile.Descendants("Line")
select new {
ID=c.Attribute("ID").Value,
Name=c.Attribute("Name").Value
}).ToList();;

Merge duplicate datatable records into XML document

I have a datatable with category/subcategory records in the format below:
hierarchy id1 cat1 id2 cat2 id3 cat3
4 3105 Mens 3195 Shorts 3130 Shorts
4 3105 Mens 3195 Shorts 3196 Swim Shorts
4 3105 Mens 3177 Knitwear 3118 Jumpers
4 3105 Mens 3177 Knitwear 3178 Cardigans
4 3105 Mens 3177 Knitwear 3814 V-Neck Knitwear
I'm trying to convert it to xml in a format like this:
<CATEGORY NAME="mens">
<CATEGORIES NAME="Shorts" />
<CATEGORIES NAME="Shorts" />
<CATEGORIES NAME="SwimShorts" />
<CATEGORIES NAME="Knitwear" />
<CATEGORIES NAME="Jumpers" />
<CATEGORIES NAME="Cardigans" />
<CATEGORIES NAME="V-Neck Knitwear" />
But the best I can get is this:
<CATEGORY NAME="Mens">
<CATEGORIES NAME="Knits" />
<CATEGORIES NAME="Crew Neck Knitwear" />
</CATEGORY>
<CATEGORY NAME="Mens">
<CATEGORIES NAME="Knits" />
<CATEGORIES NAME="Cardigans" />
As you can see there are duplicates which I don't want. I know I need to merge or de-duplicate somehow.
I'm returning the data as AsEnumerable() and then doing a foreach and creating an XElement for the top-level category and child XElements for the the subcategories:
var e = new XElement("CATEGORY", new XAttribute("ID", item["did1"]), new XAttribute("NAME", item["name1"]),
item["did2"].ToString() != "" ? new XElement("CATEGORIES", new XAttribute("ID", item["did2"]), new XAttribute("NAME", item["name2"])) : null,
item["did3"].ToString() != "" ? new XElement("CATEGORIES", new XAttribute("ID", item["did3"]), new XAttribute("NAME", item["name3"])) : null,
item["did4"].ToString() != "" ? new XElement("CATEGORIES", new XAttribute("ID", item["did4"]), new XAttribute("NAME", item["name4"])) : null
);
I'm not fussy about what technique I used to product the results.
How about something like this
var X = from item in Data
group item by item.cat1 into g
select new XElement(
"CATEGORY",
new XAttribute("NAME", g.Key),
from it in g
group it by it.cat2 into k
select new XElement("CATEGORIES2", new XAttribute("NAME", k.Key),
from i in k.Select(x=>x.cat3).Distinct()
select new XElement("CATEGORIES3", new XAttribute("NAME",i))
)
);

How to perform a hierarchical LINQ to XML query?

I know I can do this iteratively, but it would be cool to do it in a single LINQ statement.
I have some XML that looks like this:
<parent name="george">
<child name="steve" age="10" />
<child name="sue" age="3" />
<pet type="dog" />
<child name="jill" age="7" />
</parent>
<!-- ... -->
and I want to write a LINQ to XML statement to turn it into
<node type="parent" label="george">
<node type="child" label="steve" years="10 />
<node type="child" label="sue" years="3" />
<node type="child" label="jill" years="7" />
<!-- no pets! -->
</parent>
<!-- ... -->
Is that possible in a single LINQ to XML statement?
I've included two from statements in a LINQ statement before, but not a second select, which seems to be what this would require.
You'll need to query the desired elements and create new elements and attributes using the queried items. Something like this should work:
var input = #"<root>
<parent name=""george"">
<child name=""steve"" age=""10"" />
<child name=""sue"" age=""3"" />
<pet type=""dog"" />
<child name=""jill"" age=""7"" />
</parent>
</root>";
var xml = XElement.Parse(input);
var query = from p in xml.Elements("parent")
select new XElement("node",
new XAttribute("type", p.Name),
new XAttribute("label", p.Attribute("name").Value),
from c in p.Elements("child")
select new XElement("node",
new XAttribute("type", c.Name),
new XAttribute("label", c.Attribute("name").Value),
new XAttribute("years", c.Attribute("age").Value)));
Quick and dirty:
doc.Elements("parent")
.Select(p =>
new XElement("node",
new XAttribute("type", p.Name),
new XAttribute("label", p.Attribute("name") != null ? p.Attribute("name").Value : ""),
p.Elements("child")
.Select(c =>
new XElement("node",
new XAttribute("type", c.Name),
new XAttribute("label", c.Attribute("name") != null ? c.Attribute("name").Value : ""),
new XAttribute("years", c.Attribute("age") != null ? c.Attribute("age").Value : ""))
)
)
);

How to put a node in a dictionary using LINQ to XML

This is the XML file which I have:
<Root>
<Level1>
<Foo ID="1" Count="20" />
<Foo ID="2" Count="28" />
<Foo ID="3" Count="25" />
</Level1>
</Root>
I only have one Level 1 element in my XML, and inside of it there several Foo nodes.
How can I get that Foo nodes in a dictionary?
I mean Dictionary<int, int>.
var doc = XDocument.Load(fileName);
var dictionary =
doc.Root
.Element("Level1")
.Elements("Foo")
.ToDictionary(
e => (int)e.Attribute("Id"),
e => (int)e.Attribute("Count"));
XElement.Parse("XML here").Descendants("Foo").Select( s => s).ToDictionary( x=> x.Attribute("ID").Value, x=> x.Attribute("Count").Value))

Categories

Resources