2016-12-02 61 views
-8

如何在c#中讀取這種類型的XML?你有任何示例代碼?如何在c#中使用名稱/值對讀取XML?

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<row rownum="1"> 
    <column colnum="1" name="PROJECT NUMBER">1</column> 
    <column colnum="2" name="ROLE">Project Manager</column> 
    <column colnum="3" name="FIRSTNAME">Angie</column> 
    <column colnum="4" name="LASTNAME">Emanual</column> 
</row><row rownum="2"> 
    <column colnum="1" name="PROJECT NUMBER">2</column> 
    <column colnum="2" name="ROLE">Developer</column> 
    <column colnum="3" name="FIRSTNAME">Ruha</column> 
    <column colnum="4" name="LASTNAME">Rao</column> 
</row> 
+6

1)這不是有效的XML。你有多個根節點。 2)我們不會爲你寫你的代碼。你到目前爲止嘗試過什麼,哪裏有麻煩? –

+5

[我如何讀取和解析C#中的XML文件?](http://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c) –

回答

0

將下面的代碼讀取XML片段

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

namespace ConsoleApplication29 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XmlReaderSettings settings = new XmlReaderSettings(); 
      settings.ConformanceLevel = ConformanceLevel.Fragment; 

      XmlReader reader = XmlTextReader.Create(FILENAME,settings); 
      List<object> results = new List<object>(); 
      while (!reader.EOF) 
      { 
       if (reader.Name != "row") 
       { 
        reader.ReadToFollowing("row"); 
       } 
       if (!reader.EOF) 
       { 
        XElement row = (XElement)XElement.ReadFrom(reader); 
        results.Add(new object[] { 
         row.Elements("column").Select(y => new { 
          rowNum = (int)row.Attribute("rownum"), 
          colNum = (int)y.Attribute("colnum"), 
          colName = (string)y.Attribute("name"), 
          value = (string)y 
         }).FirstOrDefault() 
        }); 

       } 
      } 
     } 

    } 
} 
相關問題