【问题标题】:c# List all occurrences within variable string in comboboxc# 列出组合框中变量字符串中的所有匹配项
【发布时间】:2016-04-01 15:22:53
【问题描述】:

我这里有一个名为 OutputKSZ 的变量字符串,其中包含一个 XML 文件的代码。此 XML 文件的代码将包含可变数量的标签 <streetName language = "EN">,后跟完全可变的街道名称,然后是 </streetName>。

现在,我还有一个 winforms 小应用程序,有一个文本框、一个按钮和一个组合框。在文本框中,我复制粘贴 XML 代码。然后我点击按钮,组合框应该会列出每个<streetName language = "EN"></streetName> 标签之间的所有不同街道名称。

所以,为了清楚起见,这里有两个可变的东西:

  1. 标签streetName的出现次数
  2. 每个streetName标签之间的每个字符串的长度。

这是我迄今为止尝试过的:

if (OutputKSZ.Contains("<address source=\""))
{
    // LIJST MET START INDEXES
    List<int> indexesStart = new List<int>();
    var AddressSourceStart = new Regex("<streetName language=\"EN\">");
    foreach (Match match in AddressSourceStart.Matches(OutputKSZ))
    { indexesStart.Add(match.Index); }

    // LIJST MET END INDEXES
    List<int> indexesEnd = new List<int>();
    var AddressSourceEnd = new Regex("</streetName>");
    foreach (Match match in AddressSourceEnd.Matches(OutputKSZ))
    { indexesEnd.Add(match.Index); }

    int[] counterI = Enumerable.Range(0, indexesStart.Count).ToArray();
    foreach (int i in counterI)
    {
        int KSZGedeelteStraatStart = indexesStart[i];
        int KSZGedeelteStraatEnd = indexesEnd[i];
        int KSZGedeelteStraatLength = KSZGedeelteStraatEnd - KSZGedeelteStraatStart - 26;
        string KSZGedeelteStraat = OutputKSZ.Substring(KSZGedeelteStraatStart + 26, KSZGedeelteStraatLength);
        foreach (int ListCounter in counterI)
        {
            List<string> ListKSZGedeelteStraat = new List<string>();
            ListKSZGedeelteStraat.Add(KSZGedeelteStraat);
            comboBox2.DataSource = ListKSZGedeelteStraat;
        }

    }

对不起里面的荷兰人。 ;)
这段代码的问题是它只显示最后一次出现,而且我真的很新鲜,我已经做了好几个小时了。

你们对如何纠正这个问题有任何想法吗?我对 c# 比较陌生,所以只要我能保留文本框、按钮和组合框,如果需要,你可以重写我的整个代码。

示例 XML:

<soapenv:Envelope>
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <external:searchPersonInformationHistoryBySsinResponse>
      <informationCustomer>
        <customerIdentification>
          <sector>15</sector>
          <institution>5</institution>
        </customerIdentification>
      </informationCustomer>
      <informationCBSS>
        <ticketCBSS>b2d07603-2205-4258-b3b9-49320ab4b919</ticketCBSS>
        <timestampReceive>2016-03-27T12:49:59.680Z</timestampReceive>
        <timestampReply>2016-03-27T12:50:00.072Z</timestampReply>
      </informationCBSS>
      <legalContext>NISSE:IDENTIFICATION</legalContext>
      <criteria>
        <ssin>somenumber</ssin>
        <datagroups>
          <addresses>true</addresses>
        </datagroups>
      </criteria>
      <status>
        <value>DATA_FOUND</value>
        <code>MSG00000</code>
        <description>Successful</description>
      </status>
      <result>
        <person register="RR">
          <ssin>somenumber</ssin>
          <addresses status="DATA_FOUND">
            <address source="NR">
              <residentialAddress>
                <countryCode>150</countryCode>
                <countryName language="FR">Belgique</countryName>
                <countryName language="NL">België</countryName>
                <countryName language="DE">Belgien</countryName>
                <cityCode>somecitycode</cityCode>
                <cityName language="NL">somecityname</cityName>
                <postalCode>somepostalcode</postalCode>
                <streetCode>somestreetcode</streetCode>
                <streetName language="NL">somestreetname</streetName>
                <houseNumber>2</houseNumber>
                <inceptionDate>2014-08-09</inceptionDate>
              </residentialAddress>
            </address>
            <address source="NR">
              <residentialAddress>
                <countryCode>150</countryCode>
                <countryName language="FR">Belgique</countryName>
                <countryName language="NL">België</countryName>
                <countryName language="DE">Belgien</countryName>
                <cityCode>someothercitycode</cityCode>
                <cityName language="NL">someothercityname</cityName>
                <postalCode>someotherpostalcode</postalCode>
                <streetCode>someotherstreetcode</streetCode>
                <streetName language="NL">someotherstreetname</streetName>
                <houseNumber>2</houseNumber>
                <inceptionDate>2014-08-09</inceptionDate>
              </residentialAddress>
            </address>
          </addresses>
        </person>
      </result>
    </external:searchPersonInformationHistoryBySsinResponse>
  </soapenv:Body>
</soapenv:Envelope>

【问题讨论】:

  • 您应该使用XML reader 来简化搜索。
  • 请给我们一个样本数据。 (即您正在使用的示例 xml 字符串)
  • 我会在未来的某个时候研究 XML 阅读器,但是看到我对 XML 文件知之甚少(我可以识别它们,但仅此而已),我想解决这个问题没有 XML 阅读器。
  • @Ali hajahmed,感谢您的建议,我添加了一个示例 XML 文件。

标签: c# list combobox indexof


【解决方案1】:

如果没有理由不解析 XML,我会将其加载到 XDocument 并使用基本的 LINQ query,如下所示:

var OutputKSZ = textBox1.Text;

var xdocument = XDocument.Parse(OutputKSZ);

var streets = xdocument.Descendants("streetName");

var streetNames = streets.Select(s => s.Value).ToList();

comboBox2.DataSource = streetNames;

如果数据不是有效的 xml,这将不起作用。

【讨论】:

  • 完美运行!非常感谢! :)
【解决方案2】:

您的循环交互有点偏离。

试试这个(包括一些测试数据,方便时删除)。

string OutputKSZ = "<address source=\">" +
                                "<streetName language=\"EN\">1</streetName> " +
                                "<streetName language=\"EN\">12</streetName> " +
                                "<streetName language=\"EN\">111</streetName> "
                                ;

            //Moved for scoping purposes
            List<string> ListKSZGedeelteStraat = new List<string>();

            if (OutputKSZ.Contains("<address source=\""))
            {
                // LIJST MET START INDEXES
                List<int> indexesStart = new List<int>();
                var AddressSourceStart = new Regex("<streetName language=\"EN\">");
                foreach (Match match in AddressSourceStart.Matches(OutputKSZ))
                {
                    indexesStart.Add(match.Index);
                }

                // LIJST MET END INDEXES
                List<int> indexesEnd = new List<int>();
                var AddressSourceEnd = new Regex("</streetName>");
                foreach (Match match in AddressSourceEnd.Matches(OutputKSZ))
                {
                    indexesEnd.Add(match.Index);
                }

                int[] counterI = Enumerable.Range(0, indexesStart.Count).ToArray();
                foreach (int i in counterI)
                {
                    int KSZGedeelteStraatStart = indexesStart[i];
                    int KSZGedeelteStraatEnd = indexesEnd[i];
                    int KSZGedeelteStraatLength = KSZGedeelteStraatEnd - KSZGedeelteStraatStart - 26;
                    string KSZGedeelteStraat = OutputKSZ.Substring(KSZGedeelteStraatStart + 26, KSZGedeelteStraatLength);

                    //Remove additional foreach loop - you were adding too many times
                    ListKSZGedeelteStraat.Add(KSZGedeelteStraat);
                }

                //Assign data source once
                comboBox2.DataSource = ListKSZGedeelteStraat;
            }

【讨论】:

  • 非常非常感谢!多亏了这段代码,我还有其他工作要做。
【解决方案3】:

这是使用 LINQ 获得所需内容的好方法。将其插入 LinqPad 进行试用:

void Main()
{
    XElement contacts =
    new XElement("Contacts",
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Address",
            new XElement("streetName", "Linden Strass",
                new XAttribute("language", "EN")),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    ),
        new XElement("Contact",
        new XElement("Name", "Max Dane"),
        new XElement("Address",
            new XElement("streetName", "Marten Strass",
                new XAttribute("language", "EN")),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    )
    );

    var streets = contacts.Elements("Contact").Elements("Address").Elements("streetName")
                          .Where(c => (string)c.Attribute("language") == "EN").ToList();

    streets.Dump();

    // Another way to express this getting all elements of that name
    var streets2 = contacts.Descendants("streetName")
                      .Where(c => (string)c.Attribute("language") == "EN").ToList();

    streets2.Dump();
}

【讨论】:

    【解决方案4】:

    我会尝试使用 RegEx 和 Matches 的不同方法。问题是它可能不是最优雅的解决方案。

    我做了一些研究,发现this。那里解释了如何检索两个已知标签之间的字符串。

    这是检索街道名称的函数:

    List<string> extractString(string xmldata){
        Regex regex = new Regex("<streetName language = \"EN\">(.*?)</streetName>");
        MatchCollection streetCollection = regex.Matches(xmldata);
    
        //Total number of matches=streetCollection.count
        List<string> streetList = new List<string>();
        for(int i=0;i<streetCollection.count;i++){
            streetList.Add(streetCollection[ctr].Value);
        }
    
        return streetList;
    }
    

    我想应该是这样的。我不完全确定语法,因为我不在我的开发计算机中,所以我没有机会自己检查代码。但这可能是一个开始。如果您遇到任何错误或其他问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2013-10-14
      • 2023-01-06
      • 2013-03-19
      • 2012-07-18
      相关资源
      最近更新 更多