我正在读取c#中的XML文件的标签,我已经读到文件末尾的代码,但是我想逐个标签地读它。实际上,我想要一个List,其中每个标签都是保存。 这是我的xml:
<XML>
<Groups>
<Group Name="Group1" ID="D7EBC5D6-0E6D-499E-B528-34BE14382755">
<Item ID="9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167"/>
<Item ID="351FEF76-B826-426F-88C4-DBAAA60F886B"/>
<Item ID="96A4CBFC-04CD-4D27-ADE6-585C05E4DBC9"/>
<Item ID="D8876943-5861-4D62-9249-C5FEF88219FA"/>
</Group>
<Group Name="Group2" ID="CC012258-14AC-44E9-BA0F-78AE7C569FCB">
<Item ID="9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167"/>
<Item ID="351FEF76-B826-426F-88C4-DBAAA60F886B"/>
</Group>
</Groups>
<Items>
<Item>
<GUID>9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167</GUID>
<Type>button</Type>
<Title>Save</Title>
<Value>submit</Value>
<Name>btnsave</Name>
<MaxLen>5</MaxLen>
</Item>
<Item>
<GUID>351FEF76-B826-426F-88C4-DBAAA60F886B</GUID>
<Type>text</Type>
<Title>Name:</Title>
<Name>txtname</Name>
<Value>Name</Value>
<MaxLen>2</MaxLen>
</Item>
</Items>
</XML>
我的C#代码:
public Guid GroupsGuid;
public Guid ItemsGuid;
List<Guid> ItemsIndex = new List<Guid>();
public string Datastring;
public override void LoadFromXML(string XMLFileAddress)
{
XmlTextReader reader = new XmlTextReader(XMLFileAddress);
while (reader.Read())
{
switch (reader.Name)
{
case "Groups":
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement)
break;
switch (reader.Name)
{
case "Group":
GroupsGuid=Guid.Parse(reader.GetAttribute("ID"));
Datastring += "<" + reader.Name + " name = " + reader.GetAttribute("Name") + " ID = " + GroupsGuid + "/>";
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement)
break;
switch (reader.Name)
{
case "Item":
ItemsGuid = Guid.Parse(reader.GetAttribute("ID"));
Datastring += "<" + reader.Name + " ID = " + reader.GetAttribute("ID") + "/>";
ItemsIndex.Add(GroupsGuid);
break;
}
}
break;
}
}
reader.Close();
break;
}
}
}
我希望在我的程序中看到标记为对象。 提前谢谢。
答案 0 :(得分:7)
这可能会有所帮助:
XDocument doc = XDocument.Load(your file);
var result = doc.Descendants().ToList();
编辑:要获得结果(根据您的评论),请尝试以下操作:
XDocument doc = XDocument.Load(your file);
var groupItems = doc.Descendants("Group")
.SelectMany(i => i.Elements("Item"))
.Attributes("ID")
.Select(j => (string)j)
.ToList();
var nodes = doc.Descendants("Items")
.Elements("Item")
.Where(i => groupItems.Contains((string)i.Element("GUID")))
.ToList();
答案 1 :(得分:1)
XmlDocument doc = new XmlDocument();
doc.Load(path);// write xml path
XmlNodeList elemList = doc.GetElementsByTagName("ID");
for (int i = 0; i < elemList.Count; i++)
{
string ID = elemList[i].Attributes["ID"].Value;
listBox1.Items.Add(ID);
}