How to put a node in a dictionary using LINQ to XML - c#

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))

Related

c# xml -> dictionary <string, Tuple<string,string,string>> in Linq

I have this XML Document
<?xml version="1.0" encoding="utf-8"?>
<Tag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<data ID="1" Tag1="A" Tag2="123" Tag3="C" />
<data ID="2" Tag1="AB" Tag2="12C3" Tag3="D" />
</Tag>
I want the convert the document into Dictionary Type <string, Tuple<string,string,string>>
So basically ID -> Tag1, Tag2, Tag3
I know there are a lot that do Key -> Value like this:
var configDictionary = xdoc.Descendants("data").ToDictionary(
datum => datum.Attribute("ID").Value,
datum => datum.Attribute("value").Value);
But i need have the value take in 3 strings.
This is rather simple. All you're missing is a declaration of the tuple using Tuple.Create:
var configDictionary = xdoc.Descendants("data")
.ToDictionary(
datum => datum.Attribute("ID").Value,
datum => Tuple.Create(datum.Attribute("Tag1").Value,
datum.Attribute("Tag2").Value,
datum.Attribute("Tag3").Value));
Note this has no validation that the attributes actually exists, which will need to be added.

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();;

c# sort XElement, with comments

I have an XElement that represents following xml:
<Node>
<Child id="1" /><!-- Comment 1 -->
<Child id="3" /><!-- Comment 3 -->
<Child id="2" /><!-- Comment 2 -->
</Node>
How can I sort the children of Node so that the XElement.ToString() method returns the following?
The comments and text behind the child must be moved along.
<Node>
<Child id="1" /><!-- Comment 1 -->
<Child id="2" /><!-- Comment 2 -->
<Child id="3" /><!-- Comment 3 -->
</Node>
Assuming each element is succeeded by the corresponding comment, try the following:
var xDoc = XDocument.Parse(/* your xml */);
var reordered = xDoc.Root
.Elements("Child")
.Select(el => new {
Element = el,
Comments = el.NodesAfterSelf()
.TakeWhile(n => n.NodeType == XmlNodeType.Comment)
})
.OrderBy(pair => (int)pair.Element.Attribute("id"))
.SelectMany(pair => new [] { pair.Element }.Concat(pair.Comments));
xDoc.Root.ReplaceAll(reordered);
EDIT: edited to allow any (incl. 0) number of comments per element; whitespace was already handled.

How to Get Element Names from XElement Using C#?

I have a Xml and i have to get the element name
<Data>
<Test key="G" modifier="control" />
<Test1 key="E" modifier="control" />
<Test3 />
<Test4 />
</Data>
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<XElement> xeCmdData = Cmd.XPathSelectElements(".//Data");
foreach (XElement xeData in xeCmdData)
{
// here i am getting the whole xml how to get Element name ...
// Like <Data>
// <Test key="G" modifier="control" />
// <Test1 key="E" modifier="control" />
// <Test3 />
// <Test4 />
// </Data>
}
How to get Element names ?
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<string> names = xd.XPathSelectElements("//Data/*")
.Select(e => e.Name.LocalName);
Or without XPath
IEnumerable<string> names = xd.Descendants("Data")
.Elements()
.Select(e => e.Name.LocalName);
Result:
Test
Test1
Test3
Test4

Remove all text nodes from XML file

I want to remove all text nodes (but not any other type of node) from an XML file. How can I do this?
Example Input:
<root>
<slideshow id="1">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>B</ThumbnailContent>
</slideshow>
</root>
Expected Output:
<root>
<slideshow id="1">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
</root>
How about:
var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
.Where(x => x.NodeType == XmlNodeType.Text ||
x.NodeType == XmlNodeType.CDATA)
.Remove();
doc.Save("clean.xml");
EDIT: Note that the above was before I realized that XCData derived from XText, leading to the simpler:
var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
.OfType<XText>()
.Remove();
doc.Save("clean.xml");
This question should help: Linq to XML - update/alter the nodes of an XML Document
You can use Linq to open the document and alter the values or remove the nodes altogether.

Categories

Resources