【发布时间】:2017-01-20 08:43:29
【问题描述】:
我想要实现的是将 JObject 转换为 XML 文档,然后从 XMl 文档中提取外部 xml。这背后的原因是通过 Azure 通知中心将结果作为推送通知发送。
我想要得到的是:
<toast>
<visual>
<binding template="ToastGeneric">
<text id="1">Message</text>
</binding>
</visual>
</toast>
我尝试过的:
JObject notificationPayload = new JObject(
new JProperty("toast",
new JObject(
new JProperty("visual",
new JObject(
new JProperty("binding",
new JObject(
new JProperty("@template", "ToastGeneric"),
new JProperty("text", notificationMessage,
new JProperty("@id", "1")))))))));
上面的代码抛出异常:Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray. 所以我之后尝试的是:
JObject notificationPayload = new JObject(
new JProperty("toast",
new JObject(
new JProperty("visual",
new JObject(
new JProperty("binding",
new JObject(
new JProperty("@template", "ToastGeneric"),
new JProperty("text", notificationMessage,
new JObject(
new JProperty("@id", "1"))))))))));
上面的代码给了我一个结果,但不是预期的结果。我得到的是:
<toast>
<visual>
<binding template="ToastGeneric">
<text>Message</text>
<text id="1" />
</binding>
</visual>
</toast>
要从 JObject 中提取 Xml,我使用以下方法:
string jsonStringToConvertToXmlString = JsonConvert.SerializeObject(notificationPayload);
XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonStringToConvertToXmlString);
return doc.OuterXml;
问题:如何将 id 属性赋予相同的 Text 属性?
【问题讨论】:
-
如果您的目标是创建 XML,为什么还要使用 JObject? LINQ to XML 将是一个更好的选择。您说您正在尝试将 JObject 转换为 XML,但您的问题似乎确实能够创建 JObject。你能澄清一下吗?
-
@JonSkeet 我正在尝试使用 JObject 构造 XML,以免自己将 XML 直接写为字符串。我不知道 LINQ to XMl,无论如何我现在会检查它。我刚刚遇到了我上面所说的问题。
-
@JonSkeet 我做了一些搜索,多亏了你,我的生活现在变得更轻松了.. 呵呵.. 我用了这个
XElement notificationPayload = new XElement("toast", new XElement("visual", new XElement("binding", new XElement("text", notificationMessage, new XAttribute("id", "1")), new XAttribute("template", "ToastGeneric")))); return notificationPayload.Value; -
是的,我已经添加了类似效果的答案。不过,我建议使用
1而不是"1",以养成让LINQ to XML 进行转换的习惯。这对于 DateTime 值之类的东西非常重要:)