首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

用C#的xml类,怎么读取xml文件中的一个属性值呢

2012-09-24 
用C#的xml类,如何读取xml文件中的一个属性值呢用C#的xml类,如何读取xml文件中的一个属性呢,XML code?xml

用C#的xml类,如何读取xml文件中的一个属性值呢
用C#的xml类,如何读取xml文件中的一个属性呢,

XML code
<?xml version="1.0" encoding="UTF-8"?><PropDataBucket name="navisworks_df_floor_cicle" version="1.0">           <PropDataRow name="smoke" index="0" type="custom">            <target name="properties">            <property name="floortype" value= "circular"></property>    <property name="length" value= ""></property>    </target>                </PropDataRow>      <PropDataRow name="navisworks_df_floor_rectangular_01" index="1" type="">    <target name="properties">      <property name="floortype" value="rectangular" />       <property name="length" value="1000.00" />     </target>  </PropDataRow></PropDataBucket>


我现在想读取PropDataRow name="smoke"下的property name="floortype"的value值,
我写的C#代码如下:
C# code
using System;using System.Xml;namespace ConsoleApplication5{    class Class1    {               [STAThread]        static void Main(string[] args)        {             myDoc.Load("F:\\xmlReader1\\test.xml");             //string Test22 = myDoc.SelectSingleNode("//PropDataBucket[name='PropDataBucket']").ChildNodes.Item(1).OuterXml;             string Test22 = myDoc.SelectSingleNode("//PropDataBucket[name='PropDataBucket']").ChildNodes.Item(1).OuterXml;             Console.WriteLine(Test22);             //XmlNode root = myDoc.DocumentElement;             //Console.WriteLine(root);             //Console.ReadKey();        }    }}

在上面的代码中,已经报错,说object reference错误,估计是我在用ChildNodes.Item(1).OuterXml的时候不对,请帮忙给看看.


[解决办法]
给你一个例子 你看看吧
[解决办法]
XML code
<?xml version="1.0" encoding="utf-8" ?><root>  <Temple>    <Temple_Name Temple_Value="0">摸版1</Temple_Name>    <Temle_Content>      <Temple_Title>摸版1</Temple_Title>      <Temple_Event>事件名称</Temple_Event>      <Temple_Date>事件</Temple_Date>    </Temle_Content>  </Temple>  <Temple>    <Temple_Name Temple_Value="1">摸版2</Temple_Name>    <Temle_Content>      <Temple_Title>摸版2</Temple_Title>      <Temple_Event>事件名称</Temple_Event>      <Temple_Date>事件</Temple_Date>    </Temle_Content>  </Temple>  <Temple>    <Temple_Name Temple_Value="2">摸版3</Temple_Name>    <Temle_Content>      <Temple_Title>摸版3</Temple_Title>      <Temple_Event>事件名称</Temple_Event>      <Temple_Date>事件</Temple_Date>    </Temle_Content>  </Temple>  <Temple>    <Temple_Name Temple_Value="3">other</Temple_Name>    <Temle_Content>    </Temle_Content>  </Temple></root>
[解决办法]
为什么不用 LINQ to XML?
[解决办法]
C# code
 string Test22 = myDoc.SelectSingleNode("//PropDataBucket[name='PropDataBucket']").ChildNodes.Item(1).OuterXml;             Console.WriteLine(Test22);
------解决方案--------------------



[解决办法]
看贴回贴,是种美德。
[解决办法]
看贴回贴,是种美德
[解决办法]
看贴回贴,是种美德
[解决办法]
学习,回帖占座,以后好来找答案
[解决办法]
///添加 xml
public void AddXmlNode(string @DataName,string @SelectString,string @DataSourceName,string @Type,string @DeleteColumn)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(this.FilePath);
XmlNode root = xmlDoc.SelectSingleNode("DataChange");//查找<DataChange>
XmlElement xe1 = xmlDoc.CreateElement("Data");//创建一个<Data>节点
xe1.SetAttribute("name", @DataName);//设置该节点Name属性
xe1.SetAttribute("DataSourceName", @DataSourceName);
XmlElement xesub1 = xmlDoc.CreateElement("SelectString");
xesub1.InnerText = @SelectString;//设置文本节点
xe1.AppendChild(xesub1);//添加到<book>节点中
XmlElement xesub2 = xmlDoc.CreateElement("Type");
xesub2.InnerText = @Type;
xe1.AppendChild(xesub2);

XmlElement xesub3 = xmlDoc.CreateElement("Remove");
xesub3.InnerText = @DeleteColumn;
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到<bookstore>节点中
//this.SourceList.Add(@DeleteColumn);
xmlDoc.Save("1.xml");
}
catch (Exception ex)
{
throw ex;
}
}
快速读取某个属性 
public void GetHistorySelect()
{
try
{

XmlReader read = XmlReader.Create(this.FilePath);
this.SourceList.Clear();
while (read.Read())
{
read.ReadToFollowing("Data");
this.SourceList.Add(read.GetAttribute("name"));
}
read.Close();
}
//读取指定属性节点
 public bool FindDataName(string @DataName)
{
try
{
XmlReader read = XmlReader.Create(this.FilePath);
string str = "";
while (read.Read())
{
read.ReadToFollowing("Data");
if (@DataName == read.GetAttribute("name"))
{
str = @DataName;
break;
}
else
{
continue;
}
}
if (str == @DataName)
{
read.Close();
return true;
}
else
{
read.Close();
return false;
}
}
catch (Exception ex)
{ throw ex; }
}
///读取指定节点及其子节点
public void FindAllByName(string @DataName,out string @DataSourceName,out string SelectString,out string @Type,out string @DeleteColumn )
{
SelectString = "";
@Type = "";
@DataSourceName = "";
@DeleteColumn = "";


try
{
XmlReader read = XmlReader.Create(this.FilePath);
while (read.Read())
{
read.ReadToFollowing("Data");
if (@DataName == read.GetAttribute("name"))
{
@DataSourceName = read.GetAttribute("DataSourceName");
read.ReadToFollowing("SelectString");
SelectString = read.ReadInnerXml();
read.ReadToFollowing("Type");
@Type = read.ReadInnerXml();
read.ReadToFollowing("Remove");
@DeleteColumn = read.ReadInnerXml();
break;
}
}
read.Close();
}
catch (Exception ex)
{
throw ex;
}
}
删除指定节点
 public void DeleteNode(string @DataName)
{
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(this.FilePath);
XmlNodeList xnl = xdoc.SelectSingleNode("DataChange").ChildNodes;
XmlNode xmd = xdoc.SelectSingleNode("DataChange");

foreach (XmlNode xn in xnl)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("name") == @DataName)
{
xe.RemoveAll();
xmd.RemoveChild(xe);
}
}
xdoc.Save(this.FilePath);
}
catch (Exception ex)
{ throw ex; }
}
-------------
xml 结构如下
<?xml version="1.0" encoding="gb2312"?>
<DataChange>
<Data name="good" DataSourceName="DataBaseConnection">
<SelectString>select * from goods</SelectString>
<Type>Insert</Type>
<Remove>code=1,shopname=0,goodscode=0,goodsname=0,count=0</Remove>
</Data>
<Data name="33" DataSourceName="DataBaseConnection">
<SelectString>select * from goods</SelectString>
<Type>Insert</Type>
<Remove>code=1,shopname=0,goodscode=0,goodsname=0,count=0</Remove>
</Data>
</DataChange>

以上是我工作中写的代码,有不懂的再问我吧


[解决办法]
顶......
[解决办法]
XDocument doc=XDocument.Load("xml");
var query = from xe in doc.Descendants("property") where xe.Attribute("name").Value == floortype&& xe.Parent.Attribute("name").Value == smoke select xe.Value;
foreach(var item in query)
{
Console.WriteLine(item.ToString);
}
[解决办法]

C# code
XmlNode node = doc.SelectSingleNode("//PropDataBucket/PropDataRow[@name='smoke']//property[@name='floortype']");orXmlNode node = doc.SelectSingleNode("//PropDataBucket/PropDataRow[@name='smoke']/target/property[@name='floortype']");
[解决办法]
///读取指定节点及其子节点
public void FindAllByName(string @DataName,out string @DataSourceName,out string SelectString,out string @Type,out string @DeleteColumn )
{
SelectString = "";
@Type = "";
@DataSourceName = "";


@DeleteColumn = "";
try
{
XmlReader read = XmlReader.Create(this.FilePath);
while (read.Read())
{
read.ReadToFollowing("Data");
if (@DataName == read.GetAttribute("name"))
{
@DataSourceName = read.GetAttribute("DataSourceName");
read.ReadToFollowing("SelectString");
SelectString = read.ReadInnerXml();
read.ReadToFollowing("Type");
@Type = read.ReadInnerXml();
read.ReadToFollowing("Remove");
@DeleteColumn = read.ReadInnerXml();
break;
}
}
read.Close();
}
catch (Exception ex)
{
throw ex;
}
这个方法是可以找到你所要的属性的接点的属性值的
XDocument doc=XDocument.Load("xml");
var query = from xe in doc.Descendants("property") where xe.Attribute("name").Value == floortype&& xe.Parent.Attribute("name").Value == smoke select xe.Value;
foreach(var item in query)
{
Console.WriteLine(item.ToString);
}

 楼上的这个写法也是正确的
[解决办法]
原ConfigFile.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<Config>
<Login>
<Server ServerName="Remote">
<IP>100.230.40.180</IP>
<Port>836</Port>
</Server>
<Server ServerName="Server1">
<IP>100.230.40.40</IP>
<Port>836</Port>
</Server>
<Server ServerName="Server2">
<IP>100.230.40.60</IP>
<Port>836</Port>
</Server>
<Server ServerName="Server3">
<IP>100.230.30.80</IP>
<Port>836</Port>
</Server>
</Login>
<Log>true</Log>
<Timeout>200000</Timeout>
</Config>

調用函數:
XmlDocument xd = new XmlDocument();
xd.Load( "ConfigFile.xml" );
XmlNodeList ServerNodeList = xd.SelectNodes( "/Config/Login/Server" );
if( ServerNodeList.Count.Equals(0) )
{
MessageBox.Show( "ServerConfig File is error , please reset it" );
return ;
}
int serverInfoNum = 1;
foreach( XmlNode ServerNode in ServerNodeList )
{
textBox1.Text = ServerNode.Attributes[0].InnerText ;
textBox2.Text = ServerNode.ChildNodes[0].InnerText;
textBox3.text = ServerNode.ChildNodes[1].InnerText ;


 

 

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SelfTest
{
public class ReadXMLMethod
{
public void ReadXML()
{
XmlDocument doc = new XmlDocument();
doc.Load("text.xml");
// 定位到第一个<Table>节点
XmlNode root = doc.FirstChild.FirstChild;
// 取得"M001"
string s = root.Attributes["name"].Value;

//定位到第一个field 节点
XmlNode node = root.FirstChild;
// 取得field name的'id'
string s2 = node.Attributes["name"].Value;
// 取得isKey的'true'
string s3 = node.Attributes["isKey"].Value;


}
}
}
这样OK了把
[解决办法]
private void getXmlContent(string strValue)
{
string strText = "";

//xml文件路径
string strFliePath = Server.MapPath("/Temple/TempleXMLFile.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(strFliePath);

XmlNodeList rootelement = xmldoc.DocumentElement.ChildNodes;//根节点

foreach (XmlElement element in rootelement) //父节点temple
{
if (element.Name.ToLower() == "temple")
{
XmlNodeList temple_nodelist = element.ChildNodes;

if (temple_nodelist.Count > 0)
{
foreach (XmlNode node in temple_nodelist)
{
if (node.Name.ToLower() == "temple_name" ) //取与选项相同的值
{
if (node.Attributes["Temple_Value"].Value == strValue)
{
XmlNode content_node = node.NextSibling;

if (content_node.HasChildNodes)
{
XmlNodeList nodeli = content_node.ChildNodes;

foreach (XmlNode mynode in nodeli)
{
strText += mynode.ChildNodes[0].Value + ":\n";
}

TextBox2.Text = strText;
}
else
{
TextBox2.Text = strText;
}
}
else
{
continue;
}
}

}
}
}
}

}
[解决办法]
看贴回贴,是种美德
[解决办法]
我顶.
[解决办法]
string path = System.Windows.Forms.Application.StartupPath + @"\test.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode xmlNode = xmlDoc.SelectSingleNode("//PropDataBucket/PropDataRow[@name='smoke']");
if(xmlNode.HasChildNodes)
{
string str = xmlNode.SelectSingleNode("target/property[@name='floortype']").Attributes["value"].InnerText;
}
[解决办法]
System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Load(path);
var results = from a in xDoc.Descendants("property")
where (a.Attribute("name").Value == "floortype") && (a.Parent.Parent.Attribute("name").Value == "smoke")
select a;

foreach (var result in results)
{
string s = result.Attribute("value").Value.ToString();
}

------解决方案--------------------


#16 的回复你看到了么?
[解决办法]

C# code
node.Attributes["value"].Value
[解决办法]
恩,是的
[解决办法]
简单XMl操作
[解决办法]
attributes

热点排行