C # XML - Reading an XML document in a bundle

I created a basic project in which I added a really simple xml file. I see the file and my one form in the project solution. I am trying to write code to read an XML file, but I can’t access it, because the visual studio doesn't seem to collect it there if that makes sense? How can I get in this file so that I can do something like

XmlDocument doc = new XmlDocument();
doc.Load("My document here")

thank

+3
source share
3 answers

, xml ? , xml ( -explorer ) . xml bin/Debug , . , "../../filename.xml", .

:
, xml , . .

+3

xml (build action = embedded resource). :

    public static XmlDocument GetEmbeddedXml(Assembly assembly, string fileName)
    {
        using (var str = GetEmbeddedFile(assembly, fileName))
        {
            using (var tr = new XmlTextReader(str))
            {
                var xml = new XmlDocument();
                xml.Load(tr);
                return xml;
            }
        }
    }

    public static Stream GetEmbeddedFile(Assembly assembly, string fileName)
    {
        string assemblyName = assembly.GetName().Name;
        Assembly a = Assembly.Load(assemblyName);
        Stream str = a.GetManifestResourceStream(assemblyName + "." + fileName);

        if (str == null)
            throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly '" + assemblyName + "'");
        return str;

    }
+3

- :

using(XmlTextReader reader = new XmlTextReader ("yourfile.xml"))
{

    while (reader.Read()) 
    {
        switch (reader.NodeType) 
        {
            case XmlNodeType.Element: // The node is an element.
                Console.Write("<" + reader.Name);
                Console.WriteLine(">");
                break;
            case XmlNodeType.Text: //Display the text in each element.
                Console.WriteLine (reader.Value);
                break;
            case XmlNodeType. EndElement: //Display the end of the element.
                Console.Write("</" + reader.Name);
                Console.WriteLine(">");
                break;
        }
    }
}

, XML ?

0

Source: https://habr.com/ru/post/1778296/


All Articles