我已经关注了 XML。它有元素节点和文本。我必须为每个element
节点(仅)创建以下类的对象。元素的名称及其值需要存储在对象中。我怎样才能做到这一点?
public class MyElement
{
public string ElementName { get; set; }
public string ElementValue { get; set; }
}
代码
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();
}
所需的结果将如下所示
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" });
更新
以下是基于所选答案的解决方案。
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;
参考