我需要将 XML 消息发送到我的 WP7 应用程序的 Web 服务,但我没有这样做的经验。
这是 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")
)
);