开发者

Reading XML using C#

<Tasks>
    <AuxFiles>
        <FileType Att开发者_高级运维achmentType='csv' FileFormat ='*.csv'>
    </AuxFiles>
</Tasks>

What is the syntax in C# to get the FileFormat if I know the AttachmentType?

Any and all help is always appreciated.


I'd use LINQ to 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();

This will give null if there is no matching element or if the first FileType with a matching AttachmentType doesn't have a FileFormat attribute.


You can use XElement and the query support for that.

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


Try this code:

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;
   }
}


You can use XPATH to query any element in your XML file.

see this ULR: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

check also this SO post: "How to query a peer XMLNode .NET"


Another way of doing it is:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜