This is the xml:
<Packages>
<Package>
<Id>1</Id>
<Prerequisites>
<Prerequisite>7</Prerequisite>
<Prerequisite>8</Prerequisite>
</Prerequisites>
</Package>
<Package>
<Id>2</Id>
.....
</Package>
....
</Packages>
And the list:
class lista
{
public int id {get; set;}
public List<int> pre{get;set;}
}
How can I add This xml pattern to a list of lista class and this is what i have got so far bot it only put one in the second list.
XDocument xdoc = XDocument.Load("Employee.xml");
var ListPckage =
(from item in xdoc.Descendants("Package")
orderby item.Element("Id").Value
select new
{
Id = item.Element("Id").Value,
Prerequisite = item.Element("Prerequisites").Element("Prerequisite").Value,
}).ToList();
foreach works for shoing them
foreach (var item in ListPckage)
{
Console.WriteLine(item.Id);
foreach (var item1 in ListPckage)
{
Console.WriteLine(item1.Prerequisites);
}
}
As John Sket mentioned in the comment to the question, one way to achieve that is to use Linq To Xml.
//string xcontent = #"xml content here";
//XDocument xdoc = XDocument.Parse(xcontent);
XDocument xdoc = XDocument.Load("FullPathToXml");
List<lista> resultlist = xdoc.Descendants("Package")
.Select(x=> new lista
{
id = Convert.ToInt32(x.Element("Id").Value),
pre = x.Descendants("Prerequisite").Select(y=>Convert.ToInt32(y.Value)).ToList()
})
.ToList();
But, i'd suggest to use XmlSerialization/XmlDeserialization.
First parse the XML to XDocument using XDocument.Parse to get XML in XDocument variable i.e.
var requiredXml = XDocument.Parse("Xml String here")
Then you can use LINQ to Xml (something like) as below:
//may be syntactic error but you can get an idea
var requiredList =
from element in requiredXml.Descandants("Package")
Select new lista { id = element.Element("ID").Value,
pre = element.Elements("Prerequisite").Select(x=> Convert.ToInt32(x.Value)).ToList() }
Related
So I'm working with reading an xml file to create a dictionary, but I can't figure out how to access the xml fields I want.
Below is the format of the XML I want to read.
<Days>
<Day Name="Monday">
<Task Order="1">TestTask</Task>
<Task Order="2">Test2</Task>
</Day>
</Days>
Below is my code so far. I've tried a lot of variations for finding task and order, such as for task: (string)e, or e.ToString(), or e.Elements("Task").Value.ToString(); And for order e.Attributes("Order").ToString();
string today = DateTime.Now.ToString("dddd");
var allItems = new Dictionary<string, int>();
XElement root = XElement.Parse(_orderxml);
IEnumerable<XElement> address =
from el in root.Elements("Day")
where el.Attribute("Name").Value == today
select el;
foreach (XElement e in address)
{
string task = ???;
string order = ???;
allItems.Add(task, (int)order);
}
So far, none of these have given me the right results, and I'm really unsure of what the proper way to get this data is, so any help would be appreciated!
Add a second loop to iterate the tasks and extract the values
static void Main()
{
string _orderxml = #"<Days> <Day Name=""Wednesday""> <Task Order=""1"">TestTask</Task> <Task Order=""2"">Test2</Task> </Day></Days>";
string today = DateTime.Now.ToString("dddd");
var allItems = new Dictionary<string, int>();
XElement root = XElement.Parse(_orderxml);
IEnumerable<XElement> address =
from el in root.Elements("Day")
where el.Attribute("Name").Value == today
select el;
foreach (XElement e in address)
{
foreach (XElement t in e.Descendants())
{
string task = t.Value.ToString();
int order = int.Parse(t.Attribute("Order").Value.ToString());
allItems.Add(task, (int)order);
}
}
}
Or you can do it with a Linq query like this
var result=root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).Descendants("Task").Select(x => new {Task=x.Value,Order=x.Attribute("Order") });
Or create a dictionary from the anonymous objects
var result = root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).Select(x => new { Task = x.Value.ToString(), Order = x.Attribute("Order") }).ToDictionary(c => c.Task, c => c.Order);
Or create a dictionary directly from the linq query
var result = root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).ToDictionary(c => c.Value.ToString(), c => int.Parse(c.Attribute("Order").Value.ToString()));
Say I have the following xml:
<Samples>
<Sample>
<SomeStuff>
<SomMoreStuff>.. </SomeMoreStuff>
</SomeStuff>
</Sample>
<Sample>
<SomeStuff>
<SomMoreStuff>.. </SomeMoreStuff>
</SomeStuff>
</Sample>
</Samples>
How can I deserilaize this but have all text inside of < Sample > remain as a string? I dont want to parse the contents of Sample
[XmlRoot(ElementName="Samples")]
public class Samples {
[XmlElement("Sample")]
public string[] Items{ get; set; }
}
I want to end of with a list like
[
"<Sample><SomeStuff><SomMoreStuff>.. </SomeMoreStuff></SomeStuff></Sample>"
"<Sample><SomeStuff><SomMoreStuff>.. </SomeMoreStuff></SomeStuff></Sample>"
]
You might want to load your Schema into the XmlDocument class and extract the inner or outer XML from it as a string.
One example could be:
var xdoc = new XmlDocument();
xdoc.LoadXml(MySchema);
var sampleNode = xdoc.SelectNodes("//sample");
var sampleText = sampleNode.ToString();
// or
var sampleText2 = sampleNode.Item(0).OuterXml;
Use debugging to check the actual value of the node, to get the right string as output.
List example:
var xdoc = new XmlDocument();
xdoc.LoadXml(MySchema);
var sampleNode = xdoc.SelectNodes("//sample");
var sampleList = new List<string>();
foreach (XmlNode item in sampleNode)
{
sampleList.Add(item.OuterXml); // or InnerXml - whatever value it is you need.
}
it could be a silly question, but i want ta ask, how can I save the same element from an .XML file with different content as an array.
Example XML:
<ithem>
<description>description1</description>
<description>description2</description>
<description>description3</description>
</ithem>
then string [] descriptions will be
descriptions[0] = "description1";
descriptions[1] = "description2";
descriptions[2] = "description3";
Please help!
Using LINQ to XML it would be:
XElement root = XElement.Load(xmlFile);
string[] descriptions = root.Descendants("description").Select(e => e.Value).ToArray();
or
string[] descriptions = root.Element("ithem").Elements("description").Select(e => e.Value).ToArray();
Use XmlDocument to parse the XML :
var map = new XmlDocument();
map.Load("path_to_xml_file"); // you can also load it directly from a string
var descriptions = new List<string>();
var nodes = map.DocumentElement.SelectNodes("ithem/description");
foreach (XmlNode node in nodes)
{
var description = Convert.ToString(node.Value);
descriptions.Add(description);
}
And you get it as an array from:
descriptions.ToArray();
Hi I have the following XML:
<EPICORTLOG>
<POS>
<ClientId>WkStn.90.1</ClientId>
<Id>POS.90.20140819.251.8279</Id>
<StartTime>2014-08-25T05:12:34</StartTime>
<Store>90</Store>
<SysDate>2014-08-19T00:00:00</SysDate>
<TillNo>1</TillNo>
<Time>2014-08-25T05:12:34</Time>
<Tran>1093</Tran>
<WkStn>1</WkStn>
<WORKSTATION>
<IsAutoLock>1</IsAutoLock>
</WORKSTATION>
<TRADE>
<ITEM>
<Class>102499</Class>
<Desc>NIKE RACER</Desc>
<FinalPrice>82.77</FinalPrice>
<Status>ACTV</Status>
<Style>EV0615</Style>
<Tag>1</Tag>
</ITEM>
</TRADE>
</POS>
</EPICORTLOG>
There are many POS nodes like above in the actual XML. I am trying to fetch the POS node with ID=POS.90.20140819.251.8279 and then the details of Item from that particular node. I have written the following query:
XDocument xdoc = XDocument.Load(XMLFile);
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where items.Attribute("Id").Value == strSelectedPOSID
select new
{
desc=items.Element("ITEM").Attribute("Desc")
};
But it is not yielding any result for me. Here strSelectedPOSID=POS.90.20140819.251.8279. Please let me know where i am going wrong.
Id and Desc are not an Attributes. they are Elements so you should use
var item = from items in xdoc.Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = (string)items.Element("ITEM").Element("Desc")
};
I got the value at last!! Following is what i used:
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = items.Element("TRADE").Element("ITEM").Element("Desc").Value.ToString()
};
Thanks for the inputs.
I'm new to LINQ. I understand it's purpose. But I can't quite figure it out. I have an XML set that looks like the following:
<Results>
<Result>
<ID>1</ID>
<Name>John Smith</Name>
<EmailAddress>john#example.com</EmailAddress>
</Result>
<Result>
<ID>2</ID>
<Name>Bill Young</Name>
<EmailAddress>bill#example.com</EmailAddress>
</Result>
</Results>
I have loaded this XML into an XDocument as such:
string xmlText = GetXML();
XDocument xml = XDocument.Parse(xmlText);
Now, I'm trying to get the results into POCO format. In an effort to do this, I'm currently using:
var objects = from results in xml.Descendants("Results")
select new Results
// I'm stuck
How do I get a collection of Result elements via LINQ? I'm particularly confused about navigating the XML structure at this point in my code.
Thank you!
This will return a IEnumerable of anonymous class:
var q = from result in xml.Descendants
select new
{
ID = result.Descendants("ID"),
Name= result.Descendants("Name"),
EmailAddress= result.Descendants("EmailAddress")
};
or if you have defined class `Result, e.g.:
class Result
{
public ID { get; set; }
public Name { get; set; }
public EmailAddress { get; set; }
}
then:
var q = from result in xml.Descendants
select new Result
{
ID = result.Descendants("ID"),
Name = result.Descendants("Name"),
EmailAddress = result.Descendants("EmailAddress")
};
(returns IEnumerable<Result>)
If your Results child elements are only Result elements, then you can get them like this:
var objects = from result in xml.Descendants
select result;
But in this lucky case you can just use xml.Descendants.
If it's not only Result elements, then this will do fine:
var object = from result in xml.Descendants
where result.Name == "Result"
select result;