我想从节点和子节点中检索数据并存储在字符串或数据表中。 请提供一个代码来从xml文件中获取值。
XML文件
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE VirtualSport SYSTEM "VirtualSport.dtd">
<VirtualSport sport="Dog" type="Result" generated="20080531T110552+0100">
<Competition venue="Warcester Green" date="20080531" status="Active" revision="1">
<Event time="1105+0100" status="Result" number="1" noOfCompetitors="6" revision="7" offtime="110508+0100" wintime="000029.00">
<Competitor number="6" name="Time At the Bar" finishPosition="1">
<Odds numerator="6" denominator="1"/>
</Competitor>
<Competitor number="1" name="Pantomime Dame" finishPosition="2">
<Odds numerator="9" denominator="2"/>
</Competitor>
<Competitor number="2" name="Scrapper" finishPosition="3">
<Odds numerator="3" denominator="1" status="2Fav"/>
</Competitor>
<Returns type="Forecast" dividend="39.50"/>
<Returns type="TriCast" dividend="122.83"/>
</Event>
</Competition>
</VirtualSport>
我想要这样的输出
number= 6
name= Time At the Bar
finishPosition= 1
首先在我的日志文件中显示数据。任何想法请帮忙。
答案 0 :(得分:1)
这是我使用Linq2Xml的代码:
var xml = @"<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE VirtualSport SYSTEM 'VirtualSport.dtd'>
<VirtualSport sport='Dog' type='Result' generated='20080531T110552+0100'>
<Competition venue='Warcester Green' date='20080531' status='Active' revision='1'>
<Event time='1105+0100' status='Result' number='1' noOfCompetitors='6' revision='7' offtime='110508+0100' wintime='000029.00'>
<Competitor number='6' name='Time At the Bar' finishPosition='1'>
<Odds numerator='6' denominator='1'/>
</Competitor>
<Competitor number='1' name='Pantomime Dame' finishPosition='2'>
<Odds numerator='9' denominator='2'/>
</Competitor>
<Competitor number='2' name='Scrapper' finishPosition='3'>
<Odds numerator='3' denominator='1' status='2Fav'/>
</Competitor>
<Returns type='Forecast' dividend='39.50'/>
<Returns type='TriCast' dividend='122.83'/>
</Event>
</Competition>
</VirtualSport>";
var doc = XDocument.Parse(xml);
var firstCompetitor = doc.Descendants().Where(d => d.Name == "Competition").Descendants().Descendants().First();
Console.WriteLine(firstCompetitor.Attribute("number").Value);
Console.WriteLine(firstCompetitor.Attribute("name").Value);
Console.WriteLine(firstCompetitor.Attribute("finishPosition").Value);
答案 1 :(得分:0)
{
DataSet ds = new DataSet();
//below line put xml path
ds.ReadXml(@"E:\Personal\Profit and Loss by Class\Profit and Loss by Class\bin\Debug\TbPL.xml");
DataTable dt = ds.Tables[0];
}
答案 2 :(得分:0)
你听说过Google吗? “C#从xml文件中读取”
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\YourXmlFile.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.NodeType == System.Xml.XmlNodeType.Element)
contents += "<"+reader.Name + ">\n";
if (reader.NodeType == System.Xml.XmlNodeType.Text)
contents += reader.Value + "\n";
}
Console.Write(contents);