我想选择如下的XML元素。请知道数据和派对是课程。有人可以帮助如何实现以下目标:
选择新数据
{
Party.Name = xElem.Element(“Name”)。值,
Party.PostBox = xElem.Element(“PostBox”)。值,
}
使用当前代码,我无法访问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; }
}
}
@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; }
}
}
答案 0 :(得分:3)
你想:
// Modifies the existing Party created in the Data constructor
select new Data
{
Party =
{
Name = xElem.Element("Name").Value,
PostBox = xElem.Element("PostBox").Value
}
}
或:
// Creates a new Party and then calls the Data.Party setter
select new Data
{
Party = new Party
{
Name = xElem.Element("Name").Value,
PostBox = xElem.Element("PostBox").Value
}
}
请注意,这与XML无关,与LINQ没有任何关系 - 它只是使用对象初始化器功能。
您可能想要考虑的一件事是使用从XElement
到string
的显式转换,而不是使用Value
- 这样如果缺少某个元素,则会获得空引用一个例外。这取决于你想要的行为,但值得了解作为一种选择。