c# - 如何从 XML 中获取值?

标签 c# xml

我正在制作一个小工具来检查 XML 文件中的 Material 编号。

我知道这对你们这些专家来说很容易,我想请你们帮助我开始这件事。我猜我的机器上安装了 .NET 2.0 框架,并安装了 VS C# Express 2005。

我有一个包含 Material 数据的 XML。它位于我的本地驱动器上。我现在可以浏览 XML 文件并将文件保存在字符串变量中。嗯,这就是我到目前为止所做的......

if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
    string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "Product.xml");

    string prodFile = files[0];
    ...
    ...

假设这是 XML 的结构:

<Record>
    <Product>
        <Material_Number>20209485</Material_Number> 
        <Product_Type>Type1</Product_Type>
        ...
        ...
    </Product>
</Record>

如何获取 Material 编号值?

最佳答案

您可以使用 XmlDocument 类将 XML 文件加载到 DOM 中。

MSDN - This class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document. Because XmlDocument implements the IXPathNavigable interface it can also be used as the source document for the XslTransform class.

示例

有很多方法可以读取您的值(value)。 我真的鼓励你阅读Working with Xml DOM

XmlNodeList list = xml.GetElementsByTagName("Product");
XmlAttributeCollection attr = list[0].Attributes;
string materialNumber = list[0].ChildNodes[0].InnerText;

XmlNodeList list  = xml.GetElementsByTagName("Material_Number"); 
string materialNumber = list[0].InnerText;

更多信息

关于c# - 如何从 XML 中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019779/

相关文章:

c# - 如何使用 MudFileUpload 选择完整路径文件

c# - View 的@Model、ViewDataDictionary、ViewData 和ViewBag 是如何相互关联的?

c# - 如何使用 LINQ 按多个项目订购?

java - Android:工作线程完成工作后如何执行回调

java - 尽管设置了必要的属性,工具栏小部件中的 TextView 选取框仍无法工作

c# - .net 构造 for while 循环超时

java - 通用列表上的 XStream 异常

java - 将 xml 数据导入 sql 数据库的语法 - 逐行

java - 我的 Android 项目在 Enum 和 string.xml 之间有重复的声明

c# - 在文件和目录列表中查找公共(public)父路径