我知道这是一个很长的问题..但是我在这里试图学习解析XML文档的众多方法之一......我在网上的很多例子都是非常简单的XML文档..但是我有一些多层次的东西,我想解析它..
我的班级代码:http://pastebin.com/VKbWzKHG
<?xml version="1.0" encoding="utf-8"?>
<PageList>
<Page>
<UpperLeft>
<Parameters>
<League>AL</League>
<Season>R</Season>
<Category>Runs</Category>
<RankOrder>n/a</RankOrder>
</Parameters>
<Info>
<Row1>
<TeamLogo>LAA.tif</TeamLogo>
<Rank>1.</Rank>
<Name>Trout</Name>
<Stat>109</Stat>
</Row1>
<Row2>
.
.
.
</Row5>
</Info>
</UpperLeft>
<UpperRight>
.
.
.
</UpperRight>
<LowerLeft>
.
.
</LowerLeft>
<LowerRight>
.
.
</LowerRight>
</Page>
</PageList>
几乎会有很多页面..我不想粘贴完整的东西,所以我试图将其剪掉..但这是结构:
page
--> upper left
--> parameters
--> league
--> season
--> category
--> rankorder
--> info
--> row 1
--> team logo
--> rank
--> name
--> stat
--> row 2 to row 5
--> upper right, lower left, lower right
end page
我怎样才能成功解析这场噩梦?一切都是我创造的一个很好,很整洁的课程......但是试着将所有东西都放回到课堂上,我只是遇到了这么多麻烦..
XDocument xdoc;
try
{
List<MLBPage> collection =
{
from e in XDocument.Load("PageList.xml").Root.Elements("PageList")
select new MLBPage
{
ul = new Quadrant //upper left
{
qp = new QuadrantParameters
{
//league, season, category, rank order here
},
qi = new QuadrantInfo
{
//team logo, rank, name, stat here
}
}
}
}
}
catch (Exception)
{
/
答案 0 :(得分:2)
您可以开始映射classes / attributes / elements:
[Serializable] //Root
[XmlRoot(ElementName = "InfXml", Namespace="the namespace URI")]
public class InfXml
{
[XmlAttribute(AttributeName = "id")] //attribute
public string Id { get; set; }
public bool ShouldSerializeId() //Should serialize, only serializes if not null.
{
return !string.IsNullOrEmpty(Id); //This is only for optional fields.
}
[XmlElement(ElementName = "Identification")] //Non optional group.
public Identification Identification{ get; set; }
[XmlElement(ElementName = "Adress")] //Optional group.
public Adress Adress{ get; set; }
public bool ShouldSerializeAdress()
{
return Adress!= null;
}
}
如果你有一个映射的class-to-Xml,你可以使用这两种方法:
const string PrefixXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
public static object Deserialize<T>(T obj, string xmlText)
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(T));
TextReader textReader = new StringReader(xmlText);
return (T)deserializer.Deserialize(textReader);
}
catch (Exception ex)
{
//Catch here.
return null;
}
}
public static XmlDocument Serialize<T>(T obj)
{
string xmlString = GerarXml.Gerar<T>(obj);
if (!xmlString.Contains("xml version="))
{
xmlString = PrefixXml + xmlString;
}
xmlString = xmlString.Replace(Environment.NewLine, string.Empty);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
return doc;
}
如果您想将XML作为字符串获取:
public static string GetXmlText(XmlDocument doc)
{
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
doc.WriteTo(xmlTextWriter);
string ret = stringWriter.ToString();
ret = ret.Replace(Environment.NewLine, string.Empty);
if (!ret.Contains("xml version="))
{
return PrefixXml + ret;
}
return ret;
}