【发布时间】:2013-07-27 08:17:52
【问题描述】:
我正在使用一个允许 XML 但不允许 Linq 的平台,所以我必须在没有 XElement 和 XDocument 的情况下解析 XML,所以我应该使用什么来代替这两个? 我还找到了一个代码,如果有人可以解释我如何转换它
// parse the document (this is your doc but I've made the xml parseable)
var doc = XDocument.Parse(@"<chars>
<character name=""MyChar1"">
<skill1 type=""attack"" damage=""30"">
description of skill1
<name>Skill name</name>
<class1 type=""The Class Type""></class1>
<class2 type=""The Class Type 2""></class2>
</skill1>
</character>
<character name=""MyChar2"">
<skill1 type=""attack"" damage=""30""></skill1>
</character>
</chars>");
// Access a skill1 type(attribute) where the name(attribute) is "MyChar"
// this is pretty easy with LINQ. We first get all descendant nodes of type "character"
var skillWhereNameIsMyChar1 = doc.Descendants("character")
// then take the single one with an attribute named "value"
.Single(ch => ch.Attribute("name") != null && ch.Attribute("name").Value == "MyChar1")
// and take that element's child element of type skill1
.Element("skill1");
// this will print <skill1 ... /skill1>. However, this is an XElement object, not a string
// so you can continue to access inner text, attributes, children etc.
Console.WriteLine(skillWhereNameIsMyChar1);
// 2. Access the description of skill1 where name(att) is "MyChar1"
// this is tricky because the description text is just floating among other tags
// if description were wrapped in <description></description>, this would be simply
// var description = skillWhereNameIsMyChar1.Element("description").Value;
// here's the hacky way I found to get it in the current xml:
// first get the full value (inner text) of the skill node (includes "Skill Name")
var fullValue = skillWhereNameIsMyChar1.Value;
// then get the concatenated full values of all child nodes (= "Skill Name")
var innerValues = string.Join("", skillWhereNameIsMyChar1.Elements().Select(e => e.Value));
// get the description by dropping off the trailing characters that are actually inner values
// by limiting the length to the full length - the length of the non-description characters
var description = fullValue.Substring(0, length: fullValue.Length - innerValues.Length);
Console.WriteLine(description);
【问题讨论】:
-
“允许 XML”是什么意思? XML 是纯文本,因此很难想象平台不允许使用文本文件...
-
这看起来像是您可以制作 XSD 的东西,然后使用
xsd.exe生成具有适当序列化属性的强类型类。应该比自己解析更不容易出错。 -
@AlexeiLevenkov 嗯,我正在使用一个提供网络服务器的平台,它向客户端发送消息,并且可以在 C# 中配置,最近他们将 XML 添加到他们的白名单中,但昨天我意识到 XML.Linq不在白名单上,太讽刺了..所以我需要另一种方式
-
@CoryNelson 这会生成解析 XML 的代码吗? :P
标签: c# xml xml-parsing