检查中存在的XML元素 [英] Check if an element exists in XML

查看:158
本文介绍了检查中存在的XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我有编辑上面的XML XML编写程序。该文件元件可以被改变到文件夹元件。我还有一个程序,读取值(文件位置),并用它做什么,我先来检查,如果该元素是一个文件或文件夹的元素。

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.

推荐答案

您可以检查元素存在的东西,如

You can check for element existence with something like

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

但我不知道你问究竟在这里...

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

这篇关于检查中存在的XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆