少し悩んだのはこのへん。絶対パスに変換する必要あり。基準ディレクトリはプロジェクト設定で変更可能。
string szFile = "../..//XMLFile1.xml";//デフォルト状態だとDEBUGが基準ディレクトリ string szFull = System.IO.Path.GetFullPath(szFile); //相対パス"..\file.txt"の絶対パスを取得する XDocument xdoc = XDocument.Load(szFull);
void ReadXML() { try { string szFile = "../..//XMLFile1.xml";//デフォルト状態だとDEBUGが基準ディレクトリ string szFull = System.IO.Path.GetFullPath(szFile); //相対パス"..\file.txt"の絶対パスを取得する XDocument xdoc = XDocument.Load(szFull); // XElement elem = foreach (var obj in xdoc.Root.Elements()) { bool exist = (bool)obj.Attribute("Title"); if (exist) // 指定したアトリビュートがあるか否か。 { Console.WriteLine(obj.Element("Title").Value); } Console.WriteLine(obj.Element("Author").Value); Console.WriteLine(obj.Element("Price").Value); } } catch (Exception e) { Console.WriteLine("{0}",e.ToString()); } } private void Button_Click(object sender, RoutedEventArgs e) { ReadXML(); }
<?xml version="1.0" encoding="utf-8" ?> <Books> <Book ISBN="978-4048677608"> <Title>ソードアート・オンライン 1</Title> <Author>川原礫</Author> <Price>620</Price> </Book> <Book ISBN="978-123123123x"> <Title>moge</Title> <Author>hoge</Author> <Price>777</Price> </Book> <Book ISBN="978-4757508651"> <Title>機工魔術士-enchanter- 1</Title> <Author>河内和泉</Author> <Price>580</Price> </Book> </Books>