XML文件样本
<NvM_DataManager_Blocks
AlignmentConstraint="ManagedBy_DataManager"
GenerateBlockAccessAPI="Yes" UseProtectedSections="Yes" UseRteForDataManagerInterface="No">
<DATA_MANAGER_EEPROM_BLOCK Block_Crc_Type="NVM_CRC16"
Block_Priority="255" Block_Type="NVM_BLOCK_NATIVE"
ErrorCallback="" FeeOrEa_BlockId=""
Name="DataManager_Block_01"
Project_specific_information=""
Resistant_To_Changed_SW="No" Storage_In="Fee" Write_Only_At_WriteAll="No">
<DATA_ELEMENT CreateCommitedApi="Yes" DataSize=""
DataSize_bit="" Data_type="uint8" Default_Value="66"
Header_file="" Name="DataManager_DataElement_01"
Number_Of_Planned_Writes="255" VariantInit="No"/>
<DATA_ELEMENT CreateCommitedApi="Yes" DataSize=""
DataSize_bit="" Data_type="uint32"
Default_Value="255" Header_file=""
Name="DataManager_DataElement_02"
Number_Of_Planned_Writes="363" VariantInit="No"/>
</DATA_MANAGER_EEPROM_BLOCK>
<小时/> 这是我的代码。
//Load xml
XDocument xdoc = XDocument.Load("C:\\Users\\John\\Desktop\\Program\\file.xml");
var blocks2 = (from r in xdoc.Descendants("DATA_MANAGER_EEPROM_BLOCK")
select new
{
Name = r.Attribute("Name").Value,
//This line below does not the produce what is req. I need some help on how to fix this.
Sub_Elements = xdoc.Descendants("DATA_MANAGER_EEPROM_BLOCK").Descendants("DATA_ELEMENT")
}).ToList();
但是,我有一些问题需要提取子元素:DataManager_DataElement_01&amp; DataManager_DataElement_02及其属性。
答案 0 :(得分:1)
尝试以下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("CrC_Type", typeof(string));
dt.Columns.Add("Priority", typeof(int));
dt.Columns.Add("Type", typeof(string));
dt.Columns.Add("Block_Name", typeof(string));
dt.Columns.Add("Data_Type", typeof(string));
dt.Columns.Add("Default_Value", typeof(int));
dt.Columns.Add("Element_Name", typeof(string));
dt.Columns.Add("Planned_Writes", typeof(int));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement block in doc.Descendants("DATA_MANAGER_EEPROM_BLOCK"))
{
string crcType = (string)block.Attribute("Block_Crc_Type");
int blockPriority = (int)block.Attribute("Block_Priority");
string blockType = (string)block.Attribute("Block_Type");
string blockName = (string)block.Attribute("Name");
foreach(XElement element in block.Elements("DATA_ELEMENT"))
{
string dataType = (string)element.Attribute("Data_type");
int defaultValue = (int)element.Attribute("Default_Value");
string elementName = (string)element.Attribute("Name");
int plannedWrites = (int)element.Attribute("Number_Of_Planned_Writes");
dt.Rows.Add(new object[] {
crcType,
blockPriority,
blockType,
blockName,
dataType,
defaultValue,
elementName,
plannedWrites
});
}
}
}
}
}