Reputation: 22661
I have following the XML. It has element nodes and text in it. I have to create object of the following class for each element
node (only). The name of the element and its value need to be stored in the object. How can I do that?
public class MyElement
{
public string ElementName { get; set; }
public string ElementValue { get; set; }
}
CODE
static void Main(string[] args)
{
XDocument pDoc = XDocument.Parse(@"<main>
Direct 1
<sub1>A</sub1>
Direct 2
<sub2>B</sub2>
<sub3>C</sub3>
00
</main>");
IEnumerable<XNode> nodes = from c in pDoc.Elements().Nodes()
select c;
IEnumerable<MyElement> entityCollection = nodes.Select(v => new MyElement()
{
ElementName = v.ToString()
}).ToList();
}
Required result will look like the following
List<MyElement> sampleRequiredList = new List<MyElement>();
sampleRequiredList.Add(new MyElement() { ElementName = "sub1", ElementValue = "A" });
sampleRequiredList.Add(new MyElement() { ElementName = "sub2", ElementValue = "B" });
sampleRequiredList.Add(new MyElement() { ElementName = "sub3", ElementValue = "C" });
UPDATE
Following is the solution based on the selected answer.
var elementsUsingRoot = pDoc.Root.Elements();
var nodesUsingRoot = pDoc.Root.Nodes();
var secondCollection = pDoc.Root.Elements()
.Select(x => new MyElement
{
ElementName = x.Name.LocalName,
ElementValue = x.Value
});
//Text Nodes
IEnumerable<XText> textNodes = from c in pDoc.Root.Nodes()
where c.NodeType == XmlNodeType.Text
select (XText)c;
//Element Nodes
IEnumerable<XElement> elementNodes = from c in pDoc.Root.Nodes()
where c.NodeType == XmlNodeType.Element
select (XElement)c;
//Element Nodes 2
IEnumerable<XElement> elementNodes2 = from c in pDoc.Root.Elements()
select c;
REFERENCE
Upvotes: 1
Views: 913
Reputation: 1503669
Sounds like you want something like:
var entityCollection = doc.Root
.Elements()
.Select(x => new MyElement {
ElementName = x.Name.LocalName,
ElementValue = x.Value
});
Upvotes: 3