我正在尝试将Xml数据转换为C#对象。
我的C#类是这样的:
Public Class XmlModel {
public string NodeName { get; set; }
public int NodeId { get; set; }
public int ParentId { get; set; }
}
我能够获取XML的所有节点并创建一个对象列表。这是我获取节点的代码。
public List<XMLModel2> ProcessXml()
{
XMLRepository xr = new XMLRepository(new POCEntities());
XmlDocument doc = new XmlDocument();
var a = xr.GetXmlFileById(1);
doc.LoadXml(a.XmlFile);
XmlNode rootNode = doc.DocumentElement;
GetChildNodeWithId(rootNode);
return NodeList;
}
public void GetChildNodeWithId(XmlNode node)
{
AddNode(node);
XmlNodeList children = node.ChildNodes;
if (children != null)
{
for (int i = 0; i < children.Count; i++)
{
GetChildNodeWithId(children[i]);
}
}
}
public void AddNode(XmlNode node)
{
XMLModel xml = new XMLModel();
xml.NodeName = node.Name;
xml.NodeValue = node.Value;
NodeList.Add(xml);
}
现在,在将xml转换为
时,我在插入所需的数据看起来像NodeId和ParentId时遇到问题
<parent>
<child>
<key> one </key>
<key> two </key>
<key> Three </key>
</child>
<child>
<key> one </key>
<key> two </key>
<key> Three </key>
</child>
</parent>
XMLModel的列表应如下所示:
NodeName:Parent,NodeId:1,ParentId:0
NodeName:Child,NodeId = 2,ParentId:1
NodeName:密钥,NodeId:3,ParentId:2
NodeName:密钥,NodeId:4,ParentId:2
NodeName:密钥,NodeId:5,ParentId:2
NodeName:Child,NodeId = 6,ParentId:1
NodeName:密钥,NodeId:7,ParentId:6
NodeName:密钥,NodeId:8,ParentId:6
NodeName:密钥,NodeId:9,ParentId:6
答案 0 :(得分:0)
您应该可以使用LINQ to XML
var xml =
XElement.Parse(@"<parent>
<child>
<key> one </key>
<key> two </key>
<key> Three </key>
</child>
<child>
<key> one </key>
<key> two </key>
<key> Three </key>
</child>
</parent>");
var elementsAndIndex =
xml
.DescendantsAndSelf()
.Select((node, index) => new { index = index + 1, node })
.ToList();
List<XmlModel> elementsWithIndexAndParentIndex =
elementsAndIndex
.Select(
elementAndIndex =>
new
{
Element = elementAndIndex.node,
Index = elementAndIndex.index,
ParentElement = elementsAndIndex.SingleOrDefault(parent => parent.node == elementAndIndex.node.Parent)
})
.Select(
elementAndIndexAndParent =>
new XmlModel
{
NodeName = elementAndIndexAndParent.Element.Name.LocalName,
NodeId = elementAndIndexAndParent.Index,
ParentId = elementAndIndexAndParent.ParentElement == null ? 0 : elementAndIndexAndParent.ParentElement.index
})
.ToList();
答案 1 :(得分:0)
您正在通过迭代手动反序列化XML内容。使用XmlSerializer进行自动属性映射。
如果您想要手动反序列化,请使用XDocument and XElement而不是XmlDocument类。这更容易,更快,并且具有现代API。 XmlDocument来自.NET 1.1,并且已经过时。