0
我想選擇XML元素如下。請知道數據和派對是班級。誰能幫如何實現以下內容:
如何使用Linq中的XML屬性
選擇新的數據
{
Party.Name = xElem.Element( 「名稱」)值,
Party.PostBox = xElem.Element( 「郵筒」。 ).Value,
}
使用當前代碼,我無法訪問Party的屬性。
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"c:\test.xml");
var q = from xElem in doc.Descendants("Party")
where (int)xElem.Attribute("ID") == 1
select new Data
{
};
}
public class Data
{
public Party Party { get; set; }
public Data()
{
this.Party = new Party();
}
}
public class Party
{
string name;
string postbox;
public string Name
{
get { return name; }
set { this.name = value; }
}
public string PostBox
{
get { return postbox; }
set { this.postbox = value; }
}
}
@Jon Skeet:以下是示例代碼。我只在運行時得到「對象引用未設置爲對象的實例」錯誤。
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"c:\test\data.xml");
var props = from xElem in doc.Descendants("Party")
where (int)xElem.Attribute("ID") == 1
select new Data
{
Party =
{
Name = xElem.Element("Name").Value.ToString(),
PostBox = xElem.Element("PostBox").Value.ToString(),
Tax =
{
CompanyID = xElem.Element("Tax").Element("CompanyID").Value.ToString()
}
}
}
}
public class Data
{
public Party Party { get; set; }
public Data()
{
this.Party= new Party();
}
}
public class Party
{
string name;
string postbox;
public Tax Tax { get; set; }
public string Name
{
get { return name; }
set { this.name = value; }
}
public string PostBox
{
get { return postbox; }
set { this.postbox = value; }
}
}
public class Tax
{
string companyid;
public string CompanyID
{
get { return companyid; }
set { this.companyid = value; }
}
}
@喬恩飛碟雙向:下面是示例代碼。我只在運行時得到「對象引用未設置爲對象的實例」錯誤。
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"c:\test\data.xml");
var props = from xElem in doc.Descendants("Party")
where (int)xElem.Attribute("ID") == 1
select new Data
{
Party =
{
Name = xElem.Element("Name").Value.ToString(),
PostBox = xElem.Element("PostBox").Value.ToString(),
Tax =
{
CompanyID = xElem.Element("Tax").Element("CompanyID").Value.ToString()
}
}
}
}
public class Data
{
public Party Party { get; set; }
public Data()
{
this.Party= new Party();
}
}
public class Party
{
string name;
string postbox;
public Tax Tax { get; set; }
public string Name
{
get { return name; }
set { this.name = value; }
}
public string PostBox
{
get { return postbox; }
set { this.postbox = value; }
}
}
public class Tax
{
string companyid;
public string CompanyID
{
get { return companyid; }
set { this.companyid = value; }
}
}
超級。非常感謝喬恩。我注意到你的慷慨建議。 – mrd
+1對於現有對象的對象初始化器('Party = {}') – Firo
當我使用Party = {}時出現錯誤「對象引用未設置爲對象的實例」。這是爲什麼? – mrd