2011-08-09 81 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;