如何筛选XmlNode



我正在XmlNode.innerXML中过滤xml节点,我得到了带有xml元素列表的innerXML,如下所示:

<runQueryRecord><id>128</id><caption_id>32</caption_id><featurename>DVC.CANYON-NIGHTFALL</featurename><featureprice>0</featureprice><sorting>0</sorting><partnumber></partnumber><imagepath>assets/images/DVC/NIGHTFALL.jpg</imagepath><selected>0</selected><hidden>0</hidden><optcatalogid>0</optcatalogid><advopt_code></advopt_code><qty>1</qty><featurecost>0</featurecost></runQueryRecord>

现在我想在featurename标签中搜索具有特定值的节点。然后我必须将其转换为json。

我的全部代码是:

XmlNode node = advanceAPI.runQuery("----", "--------",sqlquery);
var sb = new StringBuilder();
            sb.Append("APIResponse(");
            sb.Append(JsonConvert.SerializeObject(node,Newtonsoft.Json.Formatting.Indented));
            sb.Append(");");

我试过以下方法:

node = node.SelectNodes("//runQueryRecord[contains(featurename,'"+ Request.QueryString["strOption"] +"')]");

但这给了我XMLNodeList,这不是将其转换为Newtonsoft的JSON的合适格式。Json。

请给出一些关于过滤XMLNode节点和获得符合条件的匹配节点的想法。

提前谢谢。

首先,如果只想要一个XmlNode而不是XmlNodeList,则可以使用SelectSingleNode而不是SelectNodes。这将给出与XPath查询匹配的第一个节点。

其次,如果要将XML转换为JSON,则需要使用JsonConvert.SerializeXmlNode而不是JsonConvert.SerializeObject

这里有一个演示:

class Program
{
    static void Main(string[] args)
    {
        string xml = @"
            <runQueryRecord>
                <id>128</id>
                <caption_id>32</caption_id>
                <featurename>DVC.CANYON-NIGHTFALL</featurename>
                <featureprice>0</featureprice>
                <sorting>0</sorting>
                <partnumber></partnumber>
                <imagepath>assets/images/DVC/NIGHTFALL.jpg</imagepath>
                <selected>0</selected>
                <hidden>0</hidden>
                <optcatalogid>0</optcatalogid>
                <advopt_code></advopt_code>
                <qty>1</qty>
                <featurecost>0</featurecost>
            </runQueryRecord>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        string qsOption = "DVC.CANYON-NIGHTFALL";
        XmlNode node = doc.SelectSingleNode("//runQueryRecord[contains(featurename,'" + qsOption + "')]");
        string json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented);
        Console.WriteLine("APIResponse(" + json + ");");
    }
}

输出:

APIResponse({
  "runQueryRecord": {
    "id": "128",
    "caption_id": "32",
    "featurename": "DVC.CANYON-NIGHTFALL",
    "featureprice": "0",
    "sorting": "0",
    "partnumber": null,
    "imagepath": "assets/images/DVC/NIGHTFALL.jpg",
    "selected": "0",
    "hidden": "0",
    "optcatalogid": "0",
    "advopt_code": null,
    "qty": "1",
    "featurecost": "0"
  }
});

相关内容

  • 没有找到相关文章