【问题标题】:Tricky to read XML from web service C#从 Web 服务 C# 读取 XML 很棘手
【发布时间】:2016-01-12 08:16:35
【问题描述】:

我到处找,找不到任何可以帮助我的东西。

我正在编写一个连接到 web 服务的程序,然后 web 服务发送一个 XML 响应。收到响应后,我必须从中检索某些值,但这就是它变得棘手的地方

这是返回的 XML 的 sn-p:

    <?xml version="1.0"?>
<MobilePortalSellingCategoriesHierarchy xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Response xmlns="http://blabla.com/service/">Successful</Response>
  <ResponseNumber xmlns="http://blabla.com/service/">0</ResponseNumber>
  <SellingCategoriesHierarchy xmlns="http://tym2sell.com/PortalService/">
    <Response>Successful</Response>
    <ResponseNumber>0</ResponseNumber>
    <SellingCategories>
      <PortalSellingCategory>
        <SellingCategoryId xsi:nil="true" />
        <SellingCategoryName>category1</SellingCategoryName>
        <DeliveryMethod />
        <DeliveryMethodNumber>0</DeliveryMethodNumber>
        <SellingCategories>
          <PortalSellingCategory>
            <SellingCategoryId xsi:nil="true" />
            <SellingCategoryName>category1_Item</SellingCategoryName>
            <DeliveryMethod />
            <DeliveryMethodNumber>0</DeliveryMethodNumber>
            <SellingCategories>
              <PortalSellingCategory>
                <SellingCategoryId>2</SellingCategoryId>
                <SellingCategoryName>Item2</SellingCategoryName>
                <DeliveryMethod>Display</DeliveryMethod>
                <DeliveryMethodNumber>1</DeliveryMethodNumber>
                <VoucherValue>0.00</VoucherValue>
                <IsVariablePrice>true</IsVariablePrice>
                <MinimumVoucherValue>1.00</MinimumVoucherValue>
                <MaximumVoucherValue>1000.00</MaximumVoucherValue>
                <VoucherValueIncrement>1.00</VoucherValueIncrement>
                <AdditionalInputItems>
                  <PortalAdditionalInputItem>
                    <InputItemId>-1</InputItemId>
                    <Label>Value:</Label>
                    <IsNumericOnly>true</IsNumericOnly>
                    <MaximumLength>7</MaximumLength>
                    <Hidden>false</Hidden>
                  </PortalAdditionalInputItem>
                  <PortalAdditionalInputItem>
                    <InputItemId>4</InputItemId>
                    <Label>Mobile Number</Label>
                    <IsNumericOnly>true</IsNumericOnly>
                    <MaximumLength>15</MaximumLength>
                    <Hidden>false</Hidden>
                  </PortalAdditionalInputItem>
                </AdditionalInputItems>
                <TwoStep>false</TwoStep>
                <SelectedIcon>SamplePicture</SelectedIcon>
                <UnSelectedIcon>SamplePicture</UnSelectedIcon>

这从 Response 下的 SellingCategories 节点重复了几次。 这是我的代码片段,我将 XML 作为字符串。

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(receivedData);

        XmlNodeList xnList = xml.SelectNodes("/MobilePortalSellingCategoriesHierarchy");
        foreach (XmlNode xn in xnList)
        {
            string sellingCategoryName = xn["SellingCategoryName"].InnerText;
            string SelectedIcon = xn["SelectedIcon"].InnerText;
            string UnSelectedIcon = xn["UnSelectedIcon"].InnerText;
            richTextBox1.AppendText(string.Format("Name: {0} {1} {2}", sellingCategoryName, SelectedIcon, UnSelectedIcon));
        }

我尝试过更改xml.SelectNodes("/MobilePortalSellingCategoriesHierarchy");xml.SelectNodes("/MobilePortalSellingCategoriesHierarchy/SellingCategoriesHierarchy/SellingCategories/PortalSellingCategory");

我需要选择每个 SellingCategoryName 并列出 SellingCategoryName(s) 和它下面的所有其他项目。

我希望得到以下内容:

类别 1

Category1_Item

项目2

示例图片

示例图片

我的只读取第一个节点,然后返回“成功”给我。

我也试过了:

XElement root = XElement.Load("FilePath");
                var sellingCategoryNames = from PortalSellingCategory in root.Elements("MobilePortalSellingCategoriesHierarchy")
                                           where (string)PortalSellingCategory.Element("SellingCategoriesHierarchy").Element("SellingCategories").Element("PortalSellingCategory") != ""
                                           select PortalSellingCategory;
                foreach (var xEle in sellingCategoryNames)
                {
                    richTextBox1.Text = (string)xEle;
                }

任何帮助将不胜感激。

【问题讨论】:

  • 我会强烈推荐在这里使用 LINQ to XML。我怀疑是命名空间让你一开始就搞砸了,而 LINQ to XML 让命名空间变得容易多了。接下来,您似乎直接在MobilePortalSellingCategoriesHierarchy 中寻找SellingCategoryName,而实际上涉及到几层......

标签: c# xml web-services xpath nodes


【解决方案1】:

你在做什么

xml.SelectNodes("/MobilePortalSellingCategoriesHierarchy");

正在选择您的根节点,这只是一个。这就是为什么您只能在列表中获得一项。层次结构重要吗?我可以看到 PortalSellingCategory 也可以在另一个 PortalSellingCategory 中。如果不是,您可以尝试以下选择:

xml.SelectNodes("//PortalSellingCategory");

这将在您的响应中搜索每个名为“PortalSellingCategory”的节点,无论它在层次结构中的哪个位置。

编辑: 是的,您应该注意命名空间,抱歉没有看到。 如果你喜欢使用 XPath 获取所有节点,你必须创建一个新的 NamespaceManager 并在它处调用你的 selectNodes:

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(data);

    XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
    ns.AddNamespace("ns", "http://tym2sell.com/PortalService/");

    XmlNodeList xnList = xml.SelectNodes("//ns:PortalSellingCategory", ns);

【讨论】:

  • 我怀疑 OP 也需要指定命名空间......而且所有这些在 LINQ to XML 中更容易完成,不需要 XPath。
  • “枚举没有结果”
  • 编辑了我的答案。是的,Linq 可能会更好,但我认为至少以这种方式尝试以检查它的工作原理是好的……如果之后它很糟糕,你仍然可以更改为 Linq。但归根结底,您仍然知道解决此问题的不止一种方法。
  • 如果层次结构很重要,我将如何工作?
  • 您可以使用各种 XPath 语句,例如“//PortalSellingCategory//PortalSellingCategory”来获取嵌入到另一个 PortalSellingCategory 中的每个 PortalSellingCategory。但要了解 XPath 的各个方面,也许可以查看 this 之类的内容以获得完整概述
【解决方案2】:

我会使用 XElement 而不是 XMLDocument,然后使用 Linq 来查询或选择以下元素:XElement xContact = ....

int contactno = (int?)xContact.Element("command").Element("contactperson").Attribute("contactpersonid") ?? -1;

if (xContact.Element("command").Element("contactperson").Element("name").Element("firstname") != null) console.writeline(xContact.Element("command").Element("contactperson").Element("name").Element("firstname").Value);

【讨论】:

    【解决方案3】:
        var doc= new XmlDocument();
        doc.Load("FilePath"); 
        var nodeList = xml.GetElementsByTagName("PortalSellingCategory");
    

    嗨,

    它返回节点的集合,您只需查询它即可获取所需的信息。 如有需要,请随时寻求帮助。

    迪米特里。

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多