-2

我有一个奇怪的问题。我无法以任何方式修改我需要使用的 XML(这导致了我的问题)。我正在处理的 XML 采用以下形式:

<DocumentRoot>
   <Parent>
      <ClassAttribute> Value </ClassAttribute>
      <ClassName> More Attributes </ClassName> <!--Can occur a varying number of times.-->
   </Parent>
   <Parent>
      <ClassAttribute> Value </ClassAttribute>
      <ClassName> More Attributes </ClassName>
      <ClassName> More Attributes </ClassName>
   </Parent>
</DocumentRoot>

我想做的是提取此信息,并使用它来实例化一个自定义类 CustomClassName,然后将其添加到 aList<CustomClassName>中,其中 XML 文档中的每个不同 <ClassName>元素(不是值)用于创建一个新的 CustomClassName以下表格:

public class CustomClassName {
   public string ClassName; //gotten from the ClassName element (NOT the value)
   public List<string> classAttributes //gotten from the value inside the ClassAttribute element
   public List<string> moreAttributes //gotten from the value inside the ClassName element

}

我希望我已经清楚地解释了我的愿望,如果没有,请戳我以获取更多信息。

是否有可能做到这一点 ?

编辑 :

对于每个“不同的”ClassName 元素,我的意思是元素 ClassName 将在 XML 文档中出现多次,尽管如此,我希望只用其相关属性(ClassAttribute 元素的值)实例化一个 ClassName 类,并且不同的 ClassName 元素的值被“附加”到实例化类中属性的末尾。

4

2 回答 2

0

试试这个

from n in doc.Root.Elements("Parent") select 
{
ClassName = n.Element("ClassName").First().Attribute("ATTRNAME").Value,
classAttributes = from a in n.Elements("ClassAttribute") select a.Value,
moreAttributes  = from a in n.Elements("ClassName") select a.Value
}
于 2012-04-19T16:51:34.500 回答
0
XElement root = XElement.Load(file); // or .Parse(string)
List<CustomClassName> list = root.Descendants("ClassName").Select(x =>
new CustomClassName()
{
    ClassName = x.Name.LocalName, // is the name, not the value    
    classAttributes = x.Parent.Element("ClassAttribute").Value, // Value is a string, not a list, you'll have to do the conversion.
    moreAttributes = x.Value // is the value, but Value is a string, not a list, you'll have to do the conversion.
})
.ToList();

这没有多大意义,为什么要将<ClassName>元素名称中的字符串“ClassName”分配给自定义类中的 ClassName 变量。但是没有更多的xml,就不可能理解更多了。

我希望这对你有帮助。诀窍是Descendants("ClassName")然后每个节点Parent.Element("ClassAttribute")都获取其属性。

于 2012-04-20T17:27:07.120 回答