How can I transform the following XML into a List
or String[]
:
1
2<
It sounds like you're more after just parsing rather than full XML serialization/deserialization. If you can use LINQ to XML, this is pretty easy:
using System;
using System.Linq;
using System.Xml.Linq;
public class Test
{
static void Main()
{
string xml = "<Ids><id>1</id><id>2</id></Ids>";
XDocument doc = XDocument.Parse(xml);
var list = doc.Root.Elements("id")
.Select(element => element.Value)
.ToList();
foreach (string value in list)
{
Console.WriteLine(value);
}
}
}
In fact the call to Elements
could omit the argument as there are only id
elements, but I thought I'd demonstrate how to specify which elements you want.
Likewise I'd normally not bother calling ToList unless I really needed a List<string>
- without it, the result is IEnumerable<string>
which is fine if you're just iterating over it once. To create an array instead, use ToArray.
This sample will work with the .NET framework 4.0:
into a List
List<string> Ids= new List<string>();
Ids= selectedNode.Descendants("Ids").Elements("Id").Select(> x=>x.Value).Where(s =>s!= string.Empty).ToList();
into a string []
string[] Ids= thisNode
.Descendants("Ids") // Ids element
.Elements("Id") // Id elements
.Select(x=>x.Value) // XElement to string
.Where(s =>s!= string.Empty) // must be not empty
.ToArray(); // string to string []
With any type of collection. For example :
<Ids>
<id>C:\videotest\file0.txt</id>
<id>C:\videotest\file1.txt</id>
</Ids>
class FileFormat
{
public FileFormat(string path)
{
this.path = path;
}
public string FullPath
{
get { return Path.GetFullPath(path); }
}
public string FileName
{
get { return Path.GetFileName(path); }
}
private string path;
}
List<FileFormat> Files =
selectedNode
.Descendants("Ids")
.Elements("Id")
.Select(x => new FileFormat(x.Value))
.Where(s => s.FileName!=string.Empty)
.ToList();
the code to convert a string array to xml
items is a string array
items.Aggregate("", (current, x) => current + ("<item>" + x + "</item>"))
You can use Properties class.
Properties prop = new Properties();
prop.loadFromXML(stream);
Set set = prop.keySet();
You can than access Strings from set for each key. Key is element name of xml.
This sample will work with the .NET framework 3.5:
System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse("<Ids> <id>1</id> <id>2</id></Ids>");
System.Collections.Generic.List<string> ids = new System.Collections.Generic.List<string>();
foreach (System.Xml.Linq.XElement childElement in element.Descendants("id"))
{
ids.Add(childElement.Value);
}