C# .NET 使用 XmlDocument 解析 XML 文件
使用 .NET 可以使用 'XmlDocument' 类来解析 XML。以下是一个简单的示例代码:
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load('path/to/xml/file.xml');
XmlNodeList nodeList = xmlDoc.GetElementsByTagName('elementName');
foreach (XmlNode node in nodeList)
{
// 解析 XML 节点的数据
string attributeValue = node.Attributes['attributeName'].Value;
string elementValue = node.InnerText;
Console.WriteLine('Attribute: ' + attributeValue);
Console.WriteLine('Element: ' + elementValue);
}
}
}
请确保将 'path/to/xml/file.xml' 替换为实际的 XML 文件路径,并将 'elementName' 和 'attributeName' 替换为实际的元素和属性名称。
此代码片段加载 XML 文件,然后使用 GetElementsByTagName 方法选择特定元素的节点列表。然后,使用节点的 Attributes 属性获取属性值,使用 InnerText 属性获取元素值。最后,使用 Console.WriteLine 将解析的数据打印到控制台上。
原文地址: https://www.cveoy.top/t/topic/o1cx 著作权归作者所有。请勿转载和采集!