当XML父节点和子节点具有相同的名称时,如何使用LINQ to XML [英] How to use LINQ to XML when XML parent and child nodes have the same name

查看:108
本文介绍了当XML父节点和子节点具有相同的名称时,如何使用LINQ to XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Microsoft Dynamics环境中将一些SQL数据提取到XML,我目前正在C#中使用LINQ To XML读取和写入我的XML文件.我需要的一个数据是来自称为SECURITYSUBROLE的视图.查看此视图​​的结构,将显示一列也称为SECURITYSUBROLE的列.我通常的提取方法已经给了我这种XML.

I am trying to extract some SQL data to XML from a Microsoft Dynamics environment, I am currently using LINQ To XML in C# to read and write to my XML files. One piece of data I need is from a view called SECURITYSUBROLE. Looking at the structure of this view shows that there is a column also named SECURITYSUBROLE. My normal method of extraction has given me this XML.

<SECURITYSUBROLE>
  <SECURITYROLE>886301</SECURITYROLE>
  <SECURITYSUBROLE>886317</SECURITYSUBROLE>
  <VALIDFROM>1900-01-01T00:00:00-06:00</VALIDFROM>
  <VALIDFROMTZID>0</VALIDFROMTZID>
  <VALIDTO>1900-01-01T00:00:00-06:00</VALIDTO>
  <VALIDTOTZID>0</VALIDTOTZID>
  <RECVERSION>1</RECVERSION>
  <RECID>886317</RECID>
</SECURITYSUBROLE>

稍后尝试导入此数据时,由于父XML节点的名称与子节点的名称相同,因此出现错误.这是导入方法的代码段:

When I try to import this data later on, I am getting errors because the parent XML node has the same name as a child node. Here is a snippet of the import method:

XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;

XmlReader reader = XmlReader.Create(path, settings);

reader.MoveToContent();
int count = 1;
List<XElement> xmlSubset = new List<XElement>();
while (reader.ReadToFollowing(xmlTag))
 {
   if (count % 1000 == 0)
   {
    xmlSubset.Add(XElement.Load(reader.ReadSubtree()));
    XDocument xmlTemp = new XDocument(new XElement(xmlTag));
    foreach (XElement elem in xmlSubset)
    {
     xmlTemp.Root.Add(elem);
     }
     xmlSubset = new List<XElement>();
     ImportTableByName(connectionString, tableName, xmlTemp);
     count = 1;
     }
   else
   {
     xmlSubset.Add(XElement.Load(reader.ReadSubtree()));
     count++;
   }
  }
}

它在XmlReader.ReadToFollowing上当前失败,由于名称混乱,它不知道下一步要去哪里.所以我的问题分为两部分:

It's currently failing on the XmlReader.ReadToFollowing, where it doesn't know where to go next because of the name confusion. So my question has two parts:

1)除了XML之外,还有其他更好的方法来提取此数据吗?

1) Is there some better way to be extracting this data other than to XML?

2)是否可以通过LINQ To XML通过某种方式区分名称完全相同的父节点和子节点?

2) Is there a way through LINQ To XML that I can somehow differentiate between the parent and child nodes named exactly the same?

推荐答案

要获取SECURITYSUBROLE的元素(在您的情况下),您可以检查元素是否有子元素:

To get the elements (in your case) for SECURITYSUBROLE you can check to see if the element's have children:

XElement root = XElement.Load(path);
var subroles = root.Descendants("SECURITYSUBROLE") // all subroles
                   .Where(x => !x.HasElements); // only subroles without children

这篇关于当XML父节点和子节点具有相同的名称时,如何使用LINQ to XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆