convert list to xml in c# - 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>

Related

How do I append XML to another XML document OUTSIDE all the nodes

Very Simple. I have 2 documents
Doc1
<Person>
<Name>Bob</Name>
</Person>
Doc2
<Animal>
<Name>Zippy</Name>
</Animal>
And I want to create
Doc3
<Person>
<Name>Bob</Name>
</Person>
<Animal>
<Name>Zippy</Name>
</Animal>
The code I have below is close but insert the XML INSIDE the other one and I don't want that
string xmlUserData = GetUserData(fileId);
string xmlPurchaseDate = GetPurchaseData();
XDocument xdocUserData = XDocument.Parse(xmlUserData);
XDocument xdocPurchaseDate = XDocument.Parse(xmlPurchaseDate);
XElement xe1 = xdocUserData.Descendants("USERDATA").FirstOrDefault();
XElement xe2 = xdocPurchaseDate.Descendants("PurchaseAdvice").FirstOrDefault();
xe1.Add(xe2.Nodes());
Yes, you can wrap elements in a root:
XDocument doc = new XDocument();
XElement rootElement = new XElement("Root");
rootElement.Add(new XElement("person"));
rootElement.Add(new XElement("animal"));
doc.Add(rootElement);
gives:
<Root>
<person />
<animal />
</Root>

Write xmlelement using LINQ C#

How the below content can be convert to xml using LINQ
List<int> calllist = new List<int>();
calllist.Add(10);
calllist.Add(5);
calllist.Add(1);
calllist.Add(20);
The output should be:
<root>
<child>
<name>1</name>
<count>1</count>
</child>
<child>
<name>5</name>
<count>1</count>
</child>
<child>
<name>10</name>
<count>1</count>
</child>
<child>
<name>20</name>
<count>1</count>
</child>
</root>
I tried something like:
XElement root = new XElement ("root",
new XElement("child",new XElement(from c in calllist select c; /*error here*/ )));
But got stuck up and unable to proceed. Can anyone share a solution to make this work?
#user833985
Try the below.
XElement root = new XElement(
"root", from c in calllist orderby c select
new XElement("child",
new XElement("name", c),
new XElement("count",calllist.Count))
);
XElement root =
new XElement("root",
calllist
.GroupBy(c => c)
.OrderBy(g => g.Key)
.Select(g => new XElement("child",
new XElement("name", g.Key),
new XElement("count",g.Count())
)
)
);

how to import node in XML

Parent XML
<order>
<class/>
<account>
<saving/>
</account>
</order>
I want to import node to parent xml
Node:
<data>
<address/>
</data>
After importing, final xml as
<order>
<class/>
<account>
<saving/>
</account>
<data>
<address/>
</data>
</order>
Please help me here
I tried as below:
XmlDocument doc = new XmlDocument();
doc.LoadXml(childXML.InnerXml);
mlNode newNodeDataset = doc.DocumentElement;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(parentXML);
XmlNode root = xdoc.DocumentElement;
xdoc.ImportNode(newNodeDataset, true);
It donesn't throwing any error but it is not importing the node.
where i am doing wrong here?
All you need to do is add the element to the existing document root using the Add method, it seems:
var doc = new XDocument(
new XElement("order",
new XElement("class"),
new XElement("account",
new XElement("saving")
)
)
);
var element = new XElement("data", new XElement("address"));
doc.Root.Add(element);
Result (in doc):
<order>
<class />
<account>
<saving />
</account>
<data>
<address />
</data>
</order>

Add XElement to another XElement in specific location

Please consider this XML:
<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
</Employees>
That is content of a XElement variable.Now I have another XElement variable with this content:
<Person>
<ID>1001</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
I want to add this XEelemnt variable to first XElement in a specific position (for example as second Person tag). How I can do this?
thanks
First you need to load the xml string, second you get the position where you want to insert the xml, then insert the new xml. Here is an example how to do it.
var reader = new StringReader(#"<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
</Employees>");
var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
Elements("Person").
First().
AddAfterSelf(new XElement("Person",
new XElement("ID", 1001),
new XElement("Name", "Aba"),
new XElement("LName", "Aba")));
var sb = new StringBuilder();
var writer = new StringWriter(sb);
xdoc.Save(writer);
Console.WriteLine(sb);
UPDATE
If you want to insert by index, just get the element first. For example you want to insert as second position, then you need to get the first index (index = 0).
var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
Elements("Person").
ElementAt(0).
AddAfterSelf(new XElement("Person",
new XElement("ID", 1001),
new XElement("Name", "Aba"),
new XElement("LName", "Aba")));
PS: For simplicity purpose I didn't add nullity check.

Adding elements to XDocument at runtime from DataTable

I am trying to generate an XML using XDocument by pulling data from a DataTable at runtime. I want to have the output in this format:
<Document>
<Alphabets>
<Data>
<Capital>AAA</Capital>
<Small>aaa</Small>
</Data>
</Alphabets>
<Language>
<Name>English</Name>
</Language>
<Alphabets>
<Data>
<Capital>BBB</Capital>
<Small>bbb</Small>
</Data>
</Alphabets>
<Language>
<Name>English</Name>
</Language>
</Document>
The Language element has to be present after every Alphabets element. I have tried very hard to achieve this but I am unable to put this Alphabets tag after every Language element. What I have achieved is this, where the Language element is falling inside Alphabets element:
<Document>
<Alphabets>
<Data>
<Capital>AAA</Capital>
<Small>aaa</Small>
</Data>
<Language>
<Name>English</Name>
</Language>
</Alphabets>
<Alphabets>
<Data>
<Capital>BBB</Capital>
<Small>bbb</Small>
</Data>
<Language>
<Name>English</Name>
</Language>
</Alphabets>
</Document>
Here is my code :
static void Main(string[] args)
{
DataTable dtAlpha = new DataTable("Alphabetss");
dtAlpha.Columns.Add("Capital", typeof(string));
dtAlpha.Columns.Add("Small", typeof(string));
dtAlpha.Rows.Add("AAA", "aaa");
dtAlpha.Rows.Add("BBB", "bbb");
XDocument doc = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("Document",
from row in dtAlpha.AsEnumerable()
select new XElement("Alphabets",
new XElement("Data",
new XElement("Capital", row.Field<string>("Capital")),
new XElement("Small", row.Field<string>("Small"))
),
new XElement("Language",
new XElement("Name", "English")
)))
);
Console.WriteLine(doc.ToString());
Console.ReadKey();
}
Please help me on this.
You can try this way :
XDocument doc = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("Document")
);
foreach(var row in dtAlpha.AsEnumerable())
{
var alphabets = new XElement("Alphabets",
new XElement("Data",
new XElement("Capital", row.Field<string>("Capital")),
new XElement("Small", row.Field<string>("Small"))
)
);
var language = new XElement("Language",
new XElement("Name", "English")
);
doc.Root.Add(alphabets);
doc.Root.Add(language);
}

Categories

Resources