我正在制作一个小工具来检查 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/