简体   繁体   English

读出XML文件(仅从项目中)

[英]Readout XML-File (Only from Project)

I have to readout an XML-file (with already existing content) from my local Visual Studio 2013 project structure, but not from harddrive-directory (as mentioned in the most tutorials/ guides, I've read in the last 2 hours...). 我必须从本地Visual Studio 2013项目结构中读取XML文件(具有已经存在的内容),而不是从硬盘目录中读取(如大多数教程/指南中所述,我在最近2个小时内已阅读过)。 )。 After the readout process, I have to search for some tag-names in it. 读出过程之后,我必须在其中搜索一些标记名。

I have to do this way, because the requirement is, that the specified local XML-file shouldn't appear after the build process in output directory... 我必须这样做,因为要求是指定的本地XML文件不应在生成过程之后出现在输出目录中。

So how can I do that? 那我该怎么办呢?

================================================================================== ================================================== ================================

This is my AccessData.xml-file (In Project-directory: "LinqToXML_Example/AccessData.xml"): 这是我的AccessData.xml文件(在Project目录中:“ LinqToXML_Example / AccessData.xml”):

<?xml version="1.0" encoding="utf-8"?>

  <Clients>


    <Client>

        <Username>Administrator</Username>

        <Password>Admin-Password</Password>

        <Settings>
          <Item1>Admin-Setting 1</Item1>
          <Item2>Admin-Setting 2</Item2>
          <Item3>Admin-Setting 3</Item3>
        </Settings>

    </Client>



    <Client>

        <Username>Service</Username>

        <Password>Srv-Password</Password>

        <Settings>
          <Item1>Srv-Setting 1</Item1>
          <Item2>Srv-Setting 2</Item2>
          <Item3>Srv-Setting 3</Item3>
        </Settings>

    </Client>



    <Client>

        <Username>Customer</Username>

        <Password>Cust-Password</Password>

        <Settings>
          <Item1>Cust-Setting 1</Item1>
          <Item2>Cust-Setting 2</Item2>
          <Item3>Cust-Setting 3</Item3>
        </Settings>

    </Client>


  </Clients>

This is my Program.cs-file: 这是我的Program.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Reflection;

namespace LinqToXML_Example
{
    public class Program
    {


        public static string SearchForUsername(string username, XElement clients)
        {

            var userName = from p in clients.Elements()
                            where p.Element("Username").Value == username
                            select p.Element("Username").Value;

            foreach (var p in userName)
            {
                return p + " found!";
            }

            return "User '" + username + "' does not exist!";
        }



        public static bool IsUsernameExisting(string username, XElement clients)
        {
            var userName = from p in clients.Elements()
                            where p.Element("Username").Value == username
                            select p.Element("Username").Value;

            foreach (var p in userName)
            {
                return true;
            }

            return false;
        }



        public static string SearchForUsernamePassword(string username, XElement clients)
        {

            if (IsUsernameExisting(username, clients))
            {
                var password = from p in clients.Elements()
                                where p.Element("Username").Value == username
                                select p.Element("Password").Value;

                foreach (var p in password)
                    return "The password of client " + username + " is: " + p;
            }

            return "Cannot get the username's password, because of a wrong Username!";
        }



        public static List<string> ReadUserSettings(string username, XElement clients)
        {

            List<string> settingsList = new List<string>();


            if (IsUsernameExisting(username, clients))
            {
                var setting = from s in clients.Elements()
                                where s.Element("Username").Value == username
                                select s.Element("Settings");

                foreach (var p in setting)
                {
                    settingsList.Add(p.Element("Item1").Value);
                    settingsList.Add(p.Element("Item2").Value);
                    settingsList.Add(p.Element("Item3").Value);
                }

                return settingsList;
            }


            var errorMsg = "Cannot get the username's settings, because of a wrong Username!";
            settingsList.Add(errorMsg);

            return settingsList;
        }





        public static void Query(string username, XElement clients)
        {
            // Search for specific Username:
            Console.WriteLine("Search for Client " + "'" + username + "' (based on Usernames):");

            string result = SearchForUsername(username, clients);
            Console.WriteLine(result);


            Console.WriteLine("");


            // Search for Password of Client:
            Console.WriteLine("Search for Password of Client " + "'" + username + "':");

            result = SearchForUsernamePassword(username, clients);
            Console.WriteLine(result);


            Console.WriteLine("");


            // Readout the Settings of Client:
            Console.WriteLine("Readout the Settings of Client " + "'" + username + "':");

            List<string> resultList = new List<string>();
            resultList = ReadUserSettings(username, clients);

            if (resultList.Count != 1)
            {
                for (int i = 0; i < resultList.Count(); i++)
                {
                    var itemcounter = i + 1;
                    Console.WriteLine("Item" + itemcounter + ": " + resultList.ElementAt(i));
                }
            }

            else Console.WriteLine(resultList.ElementAt(0));



            Console.Read();
        }




        static void Main()
        {

            var asm = Assembly.GetExecutingAssembly();

  // Bug fix: "AccessData.xml" has to be changed to: "LinqToXML_Example.AccessData.xml" 
            var textStream = asm.GetManifestResourceStream("AccessData.xml");

       // Bug fix: Has to be changed to: var xmlReader = new XmlTextReader(textStream);
            var xmlReader = new XmlReader(textStream);

            XElement clients = XElement.Load(xmlReader);

            Query("Administrator", clients);
        }
    }
}

I've changed the properties of AccessData.xml file to: 我已经将AccessData.xml文件的属性更改为:

Build Action = "Resource" // Bug fix: Has to be changed to: 'Embeded Resource'

Copy to output directory = "Never"

Unfortunately I have no access to my xml-file :(( 不幸的是,我无法访问我的xml文件:((

Having scanned your code roughly, the following line seems to be the problem: 粗略扫描了代码之后,以下几行似乎是问题所在:

var textStream = asm.GetManifestResourceStream("AccessData.xml");

By default, resource names are prefixed with the project's default namespace. 默认情况下,资源名称以项目的默认名称空间为前缀。 Also, the project folders that the file is contained in are included in the name. 此外,文件所在的项目文件夹也包括在名称中。 So in your case, it is likely that the resource name is "LinqToXML_Example.AccessData.xml" instead of "AccessData.xml". 因此,在您的情况下,资源名称很可能是“ LinqToXML_Example.AccessData.xml”而不是“ AccessData.xml”。

Also, you should set the build action to Embedded Resource . 另外,您应该将构建操作设置为Embedded Resource

If you want to find all the resource names that are included in your project file, you can use this code and check the return value when debugging: 如果要查找项目文件中包含的所有资源名称,则可以使用此代码并在调试时检查返回值:

string[] names = asm.GetManifestResourceNames();

See this link for details. 有关详细信息,请参见此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM