大家好!
<Root>
<Layers>
<Layer>
<LayerName>a</LayerName>
</Layer>
<Layer>
<LayerName>b</LayerName>
</Layer>
<Layer>
<LayerName>c</LayerName>
</Layer>
</Layers>
<Variables>
<Variable>
<VariableName>d</VariableName>
</Variable>
<Variable>
<VariableName>e</VariableName>
</Variable>
<Variable>
<VariableName>f</VariableName>
</Variable>
</Variables>
</Root>
我想编写一个将以上XML文件解析为C#文本框的代码。我要打印图层名称和变量名称,并用逗号分隔。我应该如何安排以下代码?
private void LoadLayers()
{
XmlDocument doc = new XmlDocument();
doc.Load("a1.xml");
foreach (XmlNode node in doc.SelectNodes("//Root/Layers/Layer"))
{
string nd = node.SelectSingleNode("LayerName").InnerText;
textBox1.Text += nd + ",";
}
string a = textBox1.Text;
textBox1.Text = a.Substring(0, a.Length - 1);
}
除了变量和图层之外,还可以有其他标签,我也希望能够获得其名称。结果应为:
a,b,c,d,e,f
先谢谢您。 PS:英语不是我的母语,所以对不起。
答案 0 :(得分:0)
首先,我建议您使用linq到xml,因为它是用于xml解析的更现代的API。 在这里,我有一个基于您提供的xml文件的示例,该示例可以产生所需的输出。
请注意,此解决方案基于所提供的xml结构,但是您可以基于节点命名约定添加元素筛选,以获得更通用的解决方案。
private void Load_button_Click(object sender, EventArgs e)
{
var xDoc = XDocument.Load("test.xml");
//First of all, we want to isolate xml data parsing and result composition. We will store our names in a list.
List<string> names = new List<string>();
//Get all tag elements (Layers, Variables)
foreach (var tag in xDoc.Root.Elements())
{
//Get all entries for the tag
foreach (var entry in tag.Elements())
//For each entry, we want to get the text of the first child (LayerName, VariableName etc) and add it to our list
names.Add(entry.Elements().First().Value);
}
//Use String.Join to compose collection elements into desired result
results_textbox.Text = String.Join(",", names);
}
希望这会有所帮助!
答案 1 :(得分:0)
我将通过递归方法使用Xml Linq:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
namespace WindowsFormsApplication19
{
public partial class Form1 : Form
{
const string FILENAME = @"c:\temp\test.xml";
public Form1()
{
InitializeComponent();
}
private void buttonReadXml_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
List<string> output = new List<string>();
output.Add(root.Name.LocalName);
RecursiveParse(root, output);
}
void RecursiveParse(XElement element, List<string> output)
{
if (element.HasElements)
{
foreach (XElement newElement in element.Elements())
{
List<string> newOutput = new List<string>(); ;
newOutput.AddRange(output);
newOutput.Add(newElement.Name.LocalName);
RecursiveParse(newElement, newOutput);
}
}
else
{
List<string> newOutput = new List<string>();
newOutput.AddRange(output);
newOutput.Add((string)element);
textBox1.Text += string.Join(",", newOutput) + "\r\n";
}
}
}
}