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

AttachmentTypeを知っている場合、FileFormatを取得するためのC#の構文は何ですか?Cを使用してXMLを読む#

すべてのヘルプは常に高く評価されています。

+0

あなたの質問です:このxmlファイルを指定すると、私はFileformat属性値指定されたAttachmentType?だから、 "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

私はXMLにLINQを使用したい:

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(); 

一致する要素または一致AttachmentTypeとの最初のFileTypeFileFormat属性を持っていない場合が存在しない場合、これはnullを与えるだろう。

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; 
関連する問題