首页 > Linux操作系统 > Linux操作系统 > XMl 文件属性的读取
有如下一段XML文件,只取其中的属性:
xml version="1.0" encoding="utf-8"?>
<Root>
<Rent>
<Item Name="a" Value="1" Test="ly">Item>
<Item Name="b" Value="2">Item>
<Item Name="c" Value="3">Item>
<Item Name="d" Value="4">Item>
<Item Name="e" Value="5">Item>
Rent>
<Sale>
<Item Name="aaa" Value="111">Item>
<Item Name="bbb" Value="222">Item>
<Item Name="ccc" Value="333">Item>
<Item Name="ddd" Value="444">Item>
<Item Name="eee" Value="555">Item>
Sale>
Root>
现在只取 Name 和 Value 值C# 代码如下:
XmlDocument xdoc = new XmlDocument();
string xmlPath = @"D:\Project\2.xml";
xdoc.Load(xmlPath);
foreach (XmlNode node1 in xdoc.DocumentElement.SelectNodes("./Rent"))
{ 
foreach (XmlNode item in node1.SelectNodes("./Item"))
{
foreach (XmlAttribute xma in item.Attributes)
{
string strName = xma.Name;
string strValue = xma.Value;
}
}
}
foreach (XmlNode node2 in xdoc.DocumentElement.SelectNodes("./Sale"))
{
foreach (XmlNode item in node2.SelectNodes("./Item"))
{
foreach (XmlAttribute xma in item.Attributes)
{
string strName = xma.Name;
string strValue = xma.Value;
}
}
}也许还有更好的办法,还没有想到。希望提供意见。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-462857/ ,如需转载,请注明出处,否则将追究法律责任。