我正在尝试从以下XML字符串中提取:url,ttype,tempTnxId,token,txnStage
的值:
<?xml version="1.0" encoding="UTF-8"?>
<MMP>
<MERCHANT>
<RESPONSE>
<url>https://payment.xyz.com/paynetz/epi/fts</url>
<param name="ttype">abc</param>
<param name="tempTxnId">12319507</param>
<param name="token">x5H9RrhgfXvamaqEl6GpY4uCoXHN%2FlEm%2BUpaaKuMQus%3D</param>
<param name="txnStage">1</param>
</RESPONSE>
</MERCHANT>
</MMP>
到目前为止,我只能使用以下代码提取索引值:
foreach (XmlNode node in doc.SelectNodes("/MMP/MERCHANT/RESPONSE/param"))
{
string tempTxnId= doc.SelectNodes("/MMP/MERCHANT/RESPONSE/param")[1].InnerText;//only works with index and not name
}
/MMP/MERCHANT/RESPONSE/param
或/MMP/MERCHANT/RESPONSE/ttype
不会返回任何内容。
此解决方案:Getting specified Node values from XML document 似乎不适合我。
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);
var result = doc.Elements("table"); ///cant find Elements, Element is is not identified by the compiler
答案 0 :(得分:0)
您可以按此属性值选择节点(假设您正在尝试这样做):
doc.SelectNodes("/MMP/MERCHANT/RESPONSE/param[@name='ttype']")
.Cast<XmlNode>().ToList()
.ForEach(x=>Console.WriteLine(x.InnerText));
答案 1 :(得分:0)
使用xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var response = doc.Descendants("RESPONSE").Select(x => new {
url = (string)x.Element("url"),
ttype = x.Elements().Where(y => (string)y.Attribute("name") == "ttype").Select(z => (string)z).FirstOrDefault(),
tempTxnId = x.Elements().Where(y => (string)y.Attribute("name") == "tempTxnId").Select(z => (string)z).FirstOrDefault(),
token = x.Elements().Where(y => (string)y.Attribute("name") == "token").Select(z => (string)z).FirstOrDefault(),
txnStage = x.Elements().Where(y => (string)y.Attribute("name") == "txnStage").Select(z => (int)z).FirstOrDefault()
}).FirstOrDefault();
}
}
}
答案 2 :(得分:0)
您评论过cannot select by name ttype
ttype
是一个值,而不是一个名字
元素名称为param
元素param
的单个属性名称为name
。
如果您需要获取属性InnerText
的{{1}} param
等于name
(或其他值),那么您可以执行以下操作:< / p>
ttype