C# 将 XML 文件读入 XmlDocument

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9105009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:58:18  来源:igfitidea点击:

Read XML file into XmlDocument

c#xmlxmldocument

提问by AJP

I am very new to C#. I have XML file (text.xml). I want to read that in XmlDocumentand store the stream in string variable.

我对 C# 很陌生。我有 XML 文件 (text.xml)。我想读取它XmlDocument并将流存储在字符串变量中。

采纳答案by Timur Sadykov

Use XmlDocument.Load()method to load XML from your file. Then use XmlDocument.InnerXmlproperty to get XML string.

使用XmlDocument.Load()方法从您的文件加载 XML。然后使用XmlDocument.InnerXml属性获取 XML 字符串。

XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;

回答by Abdul Hfuda

Hope you dont mind Xml.Linq and .net3.5+

希望你不介意 Xml.Linq 和 .net3.5+

XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);

Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects

根据您感兴趣的内容,您可以跳过整个“字符串”var 部分而只使用 XLinq 对象

回答by Pupper

If your .NET version is newer than 3.0 you can try using System.Xml.Linq.XDocumentinstead of XmlDocument. It is easier to process data with XDocument.

如果你的.NET版本比3.0更新,你可以尝试使用System.Xml.Linq.XDocument替代XmlDocument。使用 处理数据更容易XDocument

回答by user3626085

XmlDocument doc = new XmlDocument();
   doc.Load("MonFichierXML.xml");

    XmlNode node = doc.SelectSingleNode("Magasin");

    XmlNodeList prop = node.SelectNodes("Items");

    foreach (XmlNode item in prop)
    {
        items Temp = new items();
        Temp.AssignInfo(item);
        lstitems.Add(Temp);
    }

回答by user3626085

var doc = new XmlDocument(); 
doc.Loadxml(@"c:\abc.xml");