2

XML:

<CONFIGURATION>
<Files>
    <File>D:\Test\TestFolder\TestFolder1\TestFile.txt</File>
    <File>D:\Test\TestFolder\TestFolder1\TestFile01.txt</File>
    <File>D:\Test\TestFolder\TestFolder1\TestFile02.txt</File>
    <File>D:\Test\TestFolder\TestFolder1\TestFile03.txt</File>
    <File>D:\Test\TestFolder\TestFolder1\TestFile04.txt</File>
</Files>
<SizeMB>3</SizeMB>
<BackupLocation>D:\Log backups\File backups</BackupLocation>
</CONFIGURATION>

Code:

private void btnLinq_Click(object sender, EventArgs e)
    {
        queryData(@"D:\WatchMe1\backupconfig1.xml");
    }

static void queryData(string xmlFile)
    {
        var xdoc = XDocument.Load(xmlFile);
        var configuration = xdoc.Element("CONFIGURATION");
        string sizeMB = configuration.Element("SizeMB").Value;
        string backupLocation = configuration.Element("BackupLocation").Value;
        //need a code here to check if element <File> exist before executing the file array
        string[] files = configuration.Element("Files").Elements("File").Select(c => c.Value).ToArray();

        foreach (string file in files)
        {
            Console.WriteLine(file);
        }
    }

I have an xml writer program that edits the above xml. The Files element can be changed to Folder element. I have another program that reads the values(file locations) and do something with it, I have to check first if the element is a Files or Folders element.

3
  • possible duplicate of Check if XML Element exists Commented Sep 5, 2012 at 7:32
  • 1
    I don't know if I understood you but when you try to check if an element contains any elements, try this: bool check = myXml.Elements("nameOfElement").Any(). You can also read the element and check if it's null or not. Commented Sep 5, 2012 at 7:35
  • @BigYellowCactus: He is not using the Xpath approach. He wants to use Linq. So maybe its not a duplicate? Commented Sep 5, 2012 at 7:38

2 Answers 2

11

You can check for element existence with something like

if(configuration.Elements("...").Any()){...}

But i'm not sure what you are asking here exactly...

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

Comments

0

This may be what you want to do:

if(configutation.Elements.First("Files") != null)
{
    string[] files = configuration.Element("Files").Elements("File").Select(c => c.Value).ToArray();
}

Hope this helps!

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.