我已經創建了一個基本項目,我添加了一個非常簡單的xml文件。我可以在項目解決方案中看到該文件和我的一個表單。我試圖編寫代碼來閱讀XML文件,但我似乎無法訪問它作爲視覺工作室似乎沒有拿起它那裏,如果這是有道理的?我如何獲取該文件,這樣我就可以做這樣的事情C#XML - 讀取包含的XML文檔
XmlDocument doc = new XmlDocument();
doc.Load("My document here")
感謝
我已經創建了一個基本項目,我添加了一個非常簡單的xml文件。我可以在項目解決方案中看到該文件和我的一個表單。我試圖編寫代碼來閱讀XML文件,但我似乎無法訪問它作爲視覺工作室似乎沒有拿起它那裏,如果這是有道理的?我如何獲取該文件,這樣我就可以做這樣的事情C#XML - 讀取包含的XML文檔
XmlDocument doc = new XmlDocument();
doc.Load("My document here")
感謝
你是說你添加的XML文件來解決呢?如果是這樣,您需要編輯xml文件的屬性(在解決方案資源管理器中右鍵單擊並選擇屬性),並將其設置爲始終在構建中複製。這將在構建時將xml文件複製到bin/Debug文件夾,並且這是程序運行的位置。如果沒有,則需要將文件路徑更改爲「../../filename.xml」,這也將起作用。
注意:
這只是你的問題的解決方案,如果XML文件是解決方案的一部分,當你運行它的程序沒有找到該文件。而且你不能使用絕對路徑。
是的,我將xml文件添加到我的解決方案。我現在右鍵單擊xml文件上的屬性並將副本設置爲輸出目錄以始終。然而,intellisense仍然不會拿起文件名,除非它不應該? – tom 2010-12-03 12:15:01
你需要做的線沿線的東西:
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文件?
將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;
}
您可以將其設置爲嵌入式資源或始終使用複製 – 2010-12-03 12:18:29