2
<Tasks>
    <AuxFiles>
        <FileType AttachmentType='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.

1
  • Is your question: Given this xml file I want to find the Fileformat attribute value for a given AttachtmentType ? So you want to find "*.csv" when you look for "csv" ? Commented Aug 9, 2011 at 19:30

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Jon Skeet's solution is more robust than this one, since it won't cause a NullReferenceException if there are no types matching or if the element doesn't have a FileFormat attribute. But the idea is the same.
1

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

Comments

0

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"

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.