2011-08-09 79 views
2
<Tasks> 
    <AuxFiles> 
     <FileType AttachmentType='csv' FileFormat ='*.csv'> 
    </AuxFiles> 
</Tasks> 

如果我知道AttachmentType,那麼C#中的語法是什麼FileFormat使用C#讀取XML

任何和所有的幫助總是讚賞。

+0

是你的問題:鑑於這個XML文件,我想找到Fileformat屬性值爲給定的AttachtmentType?所以當你尋找「csv」時你想找到「* .csv」? – Eddy

回答

1

試試這個代碼:

string fileFormat = string.Empty; 


XmlDocument xDoc = new XmlDocument(); 
xDoc.Load(fileName); 

XmlNodeList auxFilesList = xDoc.GetElementsByTagName("AuxFiles"); 
for (int i = 0; i < auxFilesList.Count; i++) 
{ 
    XmlNode item = classList.Item(i); 
    if (item.Attributes["AttachmentType"].Value == "csv") 
    { 
     fileFormat = item.Attributes["FileFormat"].Value; 
    } 
} 
2

您可以使用XElement以及對此的查詢支持。

 XElement element = XElement.Parse(@"<Tasks> 
    <AuxFiles> 
    <FileType AttachmentType='csv' FileFormat ='*.csv' /> 
    </AuxFiles> 
</Tasks>"); 
     string format = element.Descendants("FileType") 
      .Where(x => x.Attribute("AttachmentType").Value == "csv") 
      .Select(x => x.Attribute("FileFormat").Value) 
      .First(); 

     Console.WriteLine(format); 
+0

Jon Skeet的解決方案比這個更強大,因爲如果沒有類型匹配或者元素沒有FileFormat屬性,它不會導致'NullReferenceException'。但這個想法是一樣的。 – carlosfigueira

5

我會使用LINQ到XML:

var doc = XDocument.Load("file.xml"); 

var format = doc.Descendants("FileType") 
       .Where(x => (string) x.Attribute("AttachmentType") == type) 
       .Select(x => (string) x.Attribute("FileFormat")) 
       .FirstOrDefault(); 

這會給null如果沒有匹配的元素,或者如果第一FileType具有匹配AttachmentType沒有FileFormat屬性。

0

做起來的另一種方式:

XmlDocument xDoc = new XmlDocument(); 
xDoc.Load("path\\to\\file.xml"); 

// Select the node where AttachmentType='csv' 
XmlNode node = xDoc.SelectSingleNode("/Tasks/AuxFiles/FileType[@AttachmentType='csv']"); 
// Read the value of the Attribute 'FileFormat' 
var fileFormat = node.Attributes["FileFormat"].Value;