2012-04-14 33 views
5

我是一個以C#和Web服務爲開端的初學者程序員。使用XmlTextReader

Service.cs文件我的web服務的,我創建了一個ReadXMLFile()方法,我想讀現有的XML文件,從中獲取數據,並將其放置到我的IService.cs創建相應的屬性(數據成員)文件。

我的問題是,我的代碼基本上沒有做任何事情。我試過尋找網站和教程,但真的沒有太多,特別是像我這樣的初學者。任何人都知道我應該如何去做這件事,因爲我迄今爲止的嘗試顯然是錯誤的。

以下是我的ReadXMLFile()方法。

void ReadXMLFile() 
{ 
    XmlTextReader reader = new XmlTextReader("ClassRoll.xml"); 
    reader.Read(); 
    while (reader.Read()) 
    { 
     if (reader.Name == "id") 
     { 
      id = reader.ReadString(); 
     } 
     else if (reader.Name == "firstname") 
     { 
      link = reader.ReadString(); 
     } 
     else if (reader.Name == "lastname") 
     { 
      description = reader.ReadString(); 
     } 
     else if (reader.Name == "count") 
     { 
      description = reader.ReadString(); 
     } 
     else if (reader.Name == "testscore") 
     { 
      description = reader.ReadString(); 
     } 
    } 
} 

這是我的xml文件的例子

<classroll> 
    <student> 
    <id>101010</id> 
    <lastname>Smith</lastname> 
    <firstname>Joe</firstname> 
    <testscores count="5"> 
     <score>65</score> 
     <score>77</score> 
     <score>67</score> 
     <score>64</score> 
     <score>80</score> 
    </testscores> 
    </student> 
</classroll> 
+0

您可能會發現[最佳做法來解析XML文件(http://stackoverflow.com/q/55828/1048330)有用 – tenorsax 2012-04-14 03:43:50

+0

你應該分享您的XML文件或它的一個樣本如果它太大,我們可以看到它的結構。 – 2012-04-14 04:06:00

+1

你不應該直接使用XmlTextReader。改用'XmlReader.Create()'。 – 2012-04-14 05:19:52

回答

3

你可能缺少IsStartElement()條件while循環:

while (reader.Read()) 
{ 
    if (reader.IsStartElement()) 
    { 
     if (reader.Name == "id") 
     { 
      id = reader.ReadString(); 
     } 
... 
} 

此外,它會更容易使用XPathLINQ to XML來讀取您的XML,當然這取決於文件。以下是一些示例:XPathLINQ

編輯:看到XML文件的詳細信息

後,您應該更新你的邏輯來跟蹤當前student及其testscores的。另外請注意,count是一個屬性。它很快就會變得混亂,我建議你看看上面提到的樣品。

+3

我同意你應該使用LINQ to XML(XElement類),除非你有一個很好的理由不要 - 我知道的唯一好理由是你的文檔太大而不能一次性把它全部寫入內存。 – Mason 2012-04-14 04:17:52

1

我想,您在使用XmlDocument的

public void ReadXML() 
{ 
    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load("<name file>.xml"); 
    xmlEntities = new List<XmlEntity>(); 

    foreach(XmlNode item in xmlDoc.ChildNodes) 
    { 
     GetChildren(item); 
    } 
} 

private void GetChildren(XmlNode node) 
{ 
    if (node.LocalName == "Строка") 
    { 
     //<you get the element here and work with it> 
    } 
    else 
    { 
     foreach (XmlNode item in node.ChildNodes) 
     { 
      GetChildren(item); 
     } 
    } 
} 
0

之所以得到最好的結果它不工作,因爲,例如:當reader.Name ==「名字」是真實的,但它不是與它的元素值true。讀者對象讀取的是下一個節點類型,即XmlNodeType.Element。所以在這種情況下查看你的XML文件,使用reader.Read();函數再次讀取下一個節點,即XmlNodeType.Text,其值是Joe。我得到你的工作版本的例子。

void ReadXMLFile() 
{ 
XmlTextReader reader = new XmlTextReader("ClassRoll.xml"); 
reader.Read(); 
while (reader.Read()) 
{ 
    if (reader.Name == "id") 
    { 
     reader.Read(); 
     if(reader.NodeType == XmlNodeType.Text) 
     { 
      id = reader.Value; 
      reader.Read(); 
     } 

    } 
} 

}