[英]WP7 - Building an XML Message
我需要向我的WP7应用程序的Web服务发送XML消息,但我没有这样的经验。
这是Web服务需要我发送XML的格式:
<pfpMessage version='1.5'>
<header>
<source>
<component type="pfsvc" role="master">
<host ip="" hostname="" serverId=""/>
</component>
</source>
</header>
<request request-id='1288730909' async='0' response-url='' language='en'>
<phoneAppValidateDeviceTokenRequest >
<phoneAppContext >
<guid>...</guid>
<deviceToken >...</deviceToken>
<version >1.0.0</version>
</phoneAppContext>
<validationResult >yes</validationResult>
</phoneAppValidateDeviceTokenRequest>
</request>
</pfpMessage>
这是我编写的代码的一小部分:
XDocument doc = new XDocument();
// start message
XElement root = doc.Element("pfpMessage");
root.SetAttributeValue("version", 1.5);
doc.Add(root);
// message header
XElement header = doc.Element("header");
root.Add(header);
XElement source = doc.Element("source");
header.Add(source);
XElement component = doc.Element("component");
component.SetAttributeValue("type", "pfsdk");
source.Add(component);
XElement element = doc.Element("host");
element.SetAttributeValue("ip", pfAuthParams.IpAddress);
element.SetAttributeValue("hostname", pfAuthParams.Hostname);
component.Add(element);
部分问题是SetAttributeValue函数不断抛出异常,即使它看起来与MSDN示例完全相同。
这是构建与格式匹配的XML消息的正确方法吗?
编辑:这会导致InvalidOperationException:
XDocument doc = new XDocument(
new XElement("pfpMessage",
new XAttribute("version", 1.5),
new XElement("header",
new XElement("source",
new XElement("component",
new XAttribute("type", "pfsdk"),
new XElement("host",
new XAttribute("ip", pfAuthParams.IpAddress),
new XAttribute("hostname", pfAuthParams.Hostname)
)
)
)
)
),
new XElement("request",
new XAttribute("request-id", y),
new XAttribute("async", 0),
new XAttribute("response-url", ""),
new XAttribute("language", "en"),
new XElement("phoneAppValidateDeviceTokenRequest",
new XElement("phoneAppValidateContext"),
new XElement("guid", (Application.Current as App).SharedGUID),
new XElement("deviceToken", (Application.Current as App).SharedURI)
),
new XElement("version", "1.0.0")
)
);
这里:
XElement root = doc.Element("pfpMessage");
root.SetAttributeValue("version", 1.5);
...你假设元素已经存在。 Element
方法在您调用它的容器中查找元素 。 你刚刚创建了这个文档,所以它是空的。 您需要创建一个新元素:
XElement root = new XElement("pfpMessage");
其他地方也一样。
这是一个更清晰的方法:
XDocument doc = new XDocument(
new XElement("pfpMessage",
new XAttribute("version", 1.5),
new XElement("header",
new XElement("source",
new XElement("component",
new XAttribute("type", "pfsdk"),
new XElement("host",
new XAttribute("ip", pfAuthParams.IpAddress),
new XAttribute("hostname", pfAuthParams.Hostname)
)
)
)
)
)
);
(显然,如果你愿意,你可以在最后折叠括号。)
这是构建文档的一种更具声明性的方式 - 它更接近LINQ to XML的精神。 当然,您可以单独手动创建每个元素并将其附加到父元素,但它更加冗长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.