2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
這里有兩種不同的解決方案。
public ProductData TestFunction()
{
ProductData result = new ProductData();
string apiResponse = "API=3CProductData&XML=%3CProductData+Name%3D%22NameTest%22%3E%0D%0A++%3CId%3EXXXXXXXXX%3C%2FId%3E%0D%0A%3C%2FProductData%3E";
string xml = HttpUtility.UrlDecode(apiResponse.Substring(apiResponse.IndexOf("XML=") + 4));
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
XmlNode newNode = document.DocumentElement;
// Name is actually an attribute on the ProductData
result.Name = ((XmlAttribute)newNode.Attributes["Name"]).InnerText;
// Id is an actual node
result.ID = ((XmlNode)newNode.FirstChild).InnerText;
using (TextReader reader = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(ProductData));
result = (ProductData)serializer.Deserialize(reader);
}
return result;
}
[Serializable]
[XmlRoot("ProductData")]
public class ProductData
{
[XmlElement("Id")]
public string ID { get; set; }
[XmlAttribute("Name")]
public string Name { get; set; }
}
這段代碼有一個(gè)非常脆弱的部分,我沒有花很多時(shí)間嘗試處理它。在我看來(lái),XML 的格式并不是很好,因此您必須在 后面添加子字符串,XML=這就是我在末尾添加 +4 的原因??赡苁且环N更順利的方法,但問(wèn)題仍然在于轉(zhuǎn)換 XML。由于 XML 非常簡(jiǎn)單,您只需通過(guò) SelectSingleNode 定位值即可。如果您想采用 StreamReader 路線,則需要確保您的類/屬性已設(shè)置屬性(即 [XmlRoot("Productdata")])

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
API=3CProductData&XML=您必須刪除字符串中的部分,然后解碼您的部分 XML
看看這段代碼的工作原理:
string strRegex = @"<ProductData Name=""NameTest"">\r\n? <Id>XXXXXXXXX</Id>\r\n</ProductData>";
ProductData result = null;
using (TextReader reader = new StringReader(strRegex))
{
? ? var serializer = new XmlSerializer(typeof(ProductData));
? ? result = (ProductData)serializer.Deserialize(reader);
}
- 2 回答
- 0 關(guān)注
- 162 瀏覽
添加回答
舉報(bào)