2012-08-27 51 views
0

所以我很難將我的遊戲轉換爲XML/Linq,我需要這樣做是因爲項目已經擴展。看起來像這樣一個簡單的問題,但沒有找到我已經加載到我的內容中的XML文件。如果我嘗試從目錄中加載XML文件,它可以正常工作,但是如何從我包含在項目中的內容文件加載?C#Linq/XML - 沒有找到文件

我是否需要以某種方式應用Content.Load以便能夠訪問文件或以不同的方式標記文件?我目前已將標誌設置爲內容(不編譯),內容導入器是XML內容 - XNA框架,內容處理器 - 無需處理,複製到輸出目錄 - 始終複製。

感謝您的幫助。我有點笨,不得不問。我把3個z放在問題的旁邊。再次感謝!

class GameObject 
{ 
    public string objectType; 
    public string objectID; 
    public bool isActive; 
} 
struct option 
{ 
    public string optionName; 
    public string type; 
    public string command; 
} 
class TitleScreen : GameObject 
{ 
    XDocument TitleData; 
    public int totalOptions; 
    List<option> optionsShared = new List<option>(); 
    int currentDrawObject; 
    public void Init(string TitleID) 
    { 
     objectType = "TitleScreen"; 
     objectID = "Title"; 
     isActive = true; 
zzz   TitleData = XDocument.Load("TitleData.xml"); zzz 
     var options = 
      from x in TitleData.Descendants("option") 
      select new 
      { 
       type = x.Descendants("otype").First().Value, 
       optionName = x.Descendants("oname").First().Value, 
       command = x.Descendants("ocommand").First().Value 
      }; 
     foreach (var x in options) 
     { 
      optionsShared.Add(new option 
      {optionName = x.optionName, 
      type = x.type, 
      command = x.command 
      }); 
     } 
     foreach (var option in options) 
     { 
      totalOptions += 1; 
     } 
    } 
    public void Draw(SpriteBatch sb, SpriteFont sf) 
    { 
     currentDrawObject = 0; 
     sb.Begin(); 
     foreach (var option in optionsShared) 
     { 
      currentDrawObject += 1; 
      sb.DrawString(sf, option.optionName, new Vector2(50, 100 * currentDrawObject), Color.White); 
     } 
     sb.End(); 
    } 

} 

回答

2

你必須將你的xml文件「TitleData.xml」標記爲Content和Always Copy。

如果您在輸出特定文件夾設置此XML,你必須指定路徑 是

TitleData = XDocument.Load(@"yourfolder\TitleData.xml"); 

在調試模式下你可以看到設置一個破發點的應用程序路徑知道如何要小心好的路徑

+0

您也可以使用Application.StartupPath,但它不是強制性的,因爲默認情況下它使用工作目錄... –

+0

因此,在這種情況下,工作的解決方案是TitleData = XDocument.Load(@「Content \ TitleData.xml 「); – SoylentGreen

2

你需要做這樣的事情

XmlDocument xdoc = new XmlDocument(); 
xdoc.Load(Environment.CurrentDirectory + "\\TitleData.xml"); 

Environment.CurrentDirectory會給p的位置roject。如果該文件位於同一個項目文件夾中,則可以使用它。

+0

這也適用,但我選擇的答案是最簡單的。但是,我可以看到這會有用。 – SoylentGreen