c#列出组合框中变量字符串中的所有事件

c# List all occurrences within variable string in combobox

我这里有一个名为 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,我会将其加载到 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,这将不起作用。

你的循环迭代有点偏离。

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

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;
            }

这是使用 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();
}

我会尝试使用 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;
}

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