[英]extracting data from an xml file
I have a string XML, which I want to convert to an actual XML, and get its values. 我有一个字符串XML,我想将其转换为实际的XML,并获取其值。
My (string)XML document looks like that: 我的(字符串)XML文档如下所示:
<Folder>
<Files>
<File Id="123"
Size="111"
Name="abc"/>
</Files>
</Folder>
This is what I'm doing: 这就是我在做什么:
XmlDocument xml = new XmlDocument();
xml.LoadXml(stringXML);
XmlNodeList xnList = xml.SelectNodes("/Folder/Files");
foreach (XmlNode xn in xnList)
{
string a = xn["File Id"].InnerText;
}
Here, my xml
variable (the XmlDocument) has my XML: < Folder>< Files>
etc... inside the "InnerXml" property. 在这里,我的
xml
变量(XmlDocument)在“ InnerXml”属性内具有我的XML: < Folder>< Files>
等...。
The xnList
(XmlNodeList) has < File Id="123" Size="111" Name="abc"/>
under its "InnerXml" property. xnList
(XmlNodeList)在其“ InnerXml”属性下具有< File Id="123" Size="111" Name="abc"/>
。
and xn
the XmlNode is exactly the same as xnList, so there is no such thing as xn["File Id"]
. 和
xn
XmlNode与xnList完全相同,因此没有xn["File Id"]
这样的东西。
How can I get the information from the XML file? 如何从XML文件中获取信息?
It's not really clear what you're trying to do, but I'd suggest using LINQ to XML - it'll make things simpler: 目前尚不清楚您要做什么,但是我建议您使用LINQ to XML-这样会使事情变得更简单:
var doc = XDocument.Parse(stringXML);
// Or doc.Root.Element("Files").Elements("File")
foreach (var file in doc.Descendants("File"))
{
int id = (int) file.Attribute("Id");
int size = (int) file.Attribute("Size");
string name = (string) file.Attribute("Name");
// Do whatever you need...
}
Or if you just want to gather the information: 或者,如果您只想收集信息:
var doc = XDocument.Parse(stringXML);
var query = doc.Descendants("File").Select(file => new {
Id = (int) file.Attribute("Id"),
Size = (int) file.Attribute("Size"),
Name = (string) file.Attribute("Name")
});
This is the correct way: 这是正确的方法:
var stringXML = "<Folder><Files><File Id=\"123\" Size=\"111\" Name=\"abc\"/></Files></Folder> ";
XmlDocument xml = new XmlDocument();
xml.LoadXml(stringXML);
XmlNodeList xnList = xml.SelectNodes("/Folder/Files");
foreach (XmlNode xn in xnList)
{
string a = xn["File"].Attributes["Id"].Value;
}
You can't straight a way fetch the attribute value for Id. 您无法直接获取ID的属性值。 You can use the attribute property to fetch that particular attribute value.
您可以使用attribute属性来获取该特定属性值。
XmlNodeList xnList = xml.SelectNodes("/Folder/Files");
foreach (XmlNode xn in xnList)
{
string a = xn.Attributes["Id"].Value; // Modify likewise
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.