我是新来的XML,无法找到一种方式来获得内容标记之间。 我的XML文件是
< XML版本=1.0编码=UTF-8&GT?;
<块1>
<文件名=C:\ w0.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
<文件名=C:\ w1.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
<文件名=C:\ w2.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
< /块1>
解决方案
的LINQ to XML是一个伟大的地方开始。请看下面的code解析您的XML。
XML字符串= @< XML版本=1.0编码=UTF-8,&GT?;
<块1>
<文件名=C:\ w0.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
<文件名=C:\ w1.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
<文件名=C:\ w2.xml>
<字GT;文字< /字GT;
<数量> 67< /数字>
< /文件>
&所述; /块1>中;
的XDocument文件= XDocument.Parse(XML);
从文件VAR块=在document.Descendants(文件)
选择新
{
名称= file.Attribute(名),价值,
字= file.Element(词),价值,
数=(INT)file.Element(数字)
};
的foreach(块var文件)
{
Console.WriteLine({0} \ t {1} \ t {2},file.Name,file.Word,file.Number);
}
可以,当然也可以直接使用XDocument.Load而不是使用解析读取XML字符串的文件加载XML。的XDocument是在System.Xml.Linq的命名空间。坦率地说,我就从那里开始,但也有其他的选择与XML System.Xml命名空间中(XmlReader.Create等)的工作。
I am new to xml and unable to find a way to get content in between tags. My XML file is
<?xml version="1.0" encoding="utf-8"?>
<block1>
<file name="c:\w0.xml">
<word>Text</word>
<number>67</number>
</file>
<file name="c:\w1.xml">
<word>Text</word>
<number>67</number>
</file>
<file name="c:\w2.xml">
<word>Text</word>
<number>67</number>
</file>
</block1>
解决方案
LINQ to XML is a great place to start. Consider the following code to parse your XML.
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<block1>
<file name=""c:\w0.xml"">
<word>Text</word>
<number>67</number>
</file>
<file name=""c:\w1.xml"">
<word>Text</word>
<number>67</number>
</file>
<file name=""c:\w2.xml"">
<word>Text</word>
<number>67</number>
</file>
</block1>";
XDocument document = XDocument.Parse(xml);
var block = from file in document.Descendants("file")
select new
{
Name = file.Attribute ("name").Value,
Word = file.Element("word").Value,
Number = (int)file.Element("number")
};
foreach (var file in block)
{
Console.WriteLine("{0}\t{1}\t{2}", file.Name, file.Word, file.Number );
}
You can, of course, load the XML directly from a file using XDocument.Load instead of using Parse to read an XML string. XDocument is in the System.Xml.Linq namespace. Frankly, I would start there, but there are other options to work with XML in the System.Xml namespace (XmlReader.Create, etc.).