![](/img/trans.png)
[英]How can I read specific elements from XML string using XMLREADER in C#
[英]xml, xmlreader read only specific part using c#
我正在使用c#從xml文件中獲取參數。 我的問題是我只想讀取當前的程序參數。 (v1.0,v1.1,v1.2 ......)
<?xml version="1.0" encoding="utf-8" ?>
<ApplicationPool>
<Resource Version="V1.0">
<Input>2000</Input>
<Input>210</Input>
<Input>65000</Input>
</Resource>
<Resource Version="V1.1">
<Input>2500</Input>
<Input>400</Input>
<Input>130000</Input>
</Resource>
</ApplicationPool>
using (XmlReader reader = XmlReader.Create("testXml.xml"))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
if (reader["Version"] == actualVersion)
{
//??
}
}
}
}
XDocument doc = XDocument.Load("testXml.xml")
var result = doc.Root.Descendants("Resource")
.Where(x => x.Attribute("Version")!= null
&& x.Attribute("Version").Value == actualVersion);
這將返回屬性Version == actualVersion
所有Resource
節點。 之后,您可以使用節點執行任何操作。
if (reader["Version"] == actualVersion)
{
while (reader.ReadToFollowing("Input"))
{
string value = reader.ReadElementContentAsString();
// or
int value = reader.ReadElementContentAsInt();
}
}
您可以使用Xml Linq方法,如:
var xmlFile= XElement.Load(xmlString);
var actualVersion = "V1.1";
var requiredXmlData = xmlFile.Elements("Resource").Where(c=>c.Attribute("Version").Value==actualVersion );
using System.Xml;
...
string actualVersion="V1.1";
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load("testXML.xml");
XmlNodeList _ngroups = rssDoc.GetElementsByTagName("Resource");
for(int i=0;i<=_ngroups.Count-1;i++)
{
if(_ngroups[i].Attributes[0].InnerText.ToString()==actualVersion)
{
for(int j=0;j<=_ngroups[i].ChildNodes.Count-1;j++)
Console.WriteLine(_ngroups[i].ChildNodes[j].InnerText);
}
}
...
使用XmlReader和xml linq的組合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
while (!reader.EOF)
{
if (reader.Name != "Resource")
{
reader.ReadToFollowing("Resource");
}
if (!reader.EOF)
{
XElement resource = (XElement)XElement.ReadFrom(reader);
string version = (string)resource.Attribute("Version");
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.