2014-03-19 40 views
0

我正在打開一個XML文件,需要從中獲取特定值。我讀給錄音師,然後我想要獲得它的價值。C#打開XML並獲取值

這是我想出到目前爲止,其中n是路徑到一個XML文件

public void ReadXMLFile(string n) 
{ 

    if (Path.GetExtension(n) == ".xml") 
    { 

     // XML File found 
     XmlDocument doc = new XmlDocument(); 

     doc.Load(n); 
     string xmlcontents = doc.InnerXml; 

     using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents))) 
     { 

      reader.ReadToFollowing("recordingowner"); 
      string t = reader.Value; 

      Console.WriteLine(t); 

     } 

    } 

} 

然而t不與包含任何數據。這是XML文件

<recording> 
<dataformat>audio</dataformat> 
<starttime>2014-03-19 11:52:42:000 +0100</starttime> 
<endtime>2014-03-19 11:58:15:000 +0100</endtime> 
<nostart>false</nostart> 
<noend>false</noend> 
<recordingtype>stnbulk</recordingtype> 
<recordingline/> 
<servicename>1000</servicename> 
<servicenumber/> 
<deliberatebreak>0</deliberatebreak> 
<calldirection>Incoming</calldirection> 
<filename>66633769853.wav</filename> 
<otherinum>0</otherinum> 
<callparty>1</callparty> 
<recordingowners> 
<recordingowner>411111111</recordingowner> 
</recordingowners> 
<parties> 
<party id="1"> 
<number>0000</number> 
<pstarttime>2014-03-19 11:58:15:982 +0100</pstarttime> 
<pendtime>2014-03-19 11:58:15:982 +0100</pendtime> 
</recording> 

任何幫助,歡迎!

+0

我會考慮的LINQ到XML('XDocument',而不是'XmlDocument'),因爲處理起來要容易一些。 – Magus

回答

0
reader.ReadElementContentAsString(); 

固定它

1

兩件事情

1)你提供的XML是作爲政黨和政黨

2)使用以下替換串T =讀者失去的夫婦結束標記無效。值;與 string t = reader.ReadElementString();

 // XML File found 
     XmlDocument doc = new XmlDocument(); 
     doc.LoadXml(val); 

     string xmlcontents = doc.InnerXml; 

     using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents))) 
     { 

      reader.ReadToFollowing("recordingowner"); 
      string t = reader.ReadElementString(); 

      Console.WriteLine(t); 

     } 
0

我可能會做到這一點(但它確實需要有效的XML)

var t = XDocument.Load(n) 
    .Element("recording") 
    .Elements("recordingowners") 
    .First() 
    .Element("recordingowner") 
    .Value