拆分字符串,如果超过指定的长度

时间:2023-01-14 21:40:14

I am generating a XML format file using String Builder. the file will look something like this :-

我正在使用String Builder生成XML格式文件。该文件将如下所示: -

  StringBuilder strBldr = new StringBuilder();
  strBldr.AppendLine("<Root>");
  strBldr.AppendLine("<ProductDetails>");
  strBldr.AppendLine("<PId>" + lblproductid.Text + "</PId>");
  strBldr.AppendLine("<PDesc>" + strtxtProductDesc + "</PDesc>");
  strBldr.AppendLine("</ProductDetails>");
  strBldr.AppendLine("</Root>");

This is in for loop, so it may contain many product details. Now I need to split this string if it exceeds the limited length suppose 100. Till now it was easy. I am able to split this using following method:-

这是for循环,因此它可能包含许多产品详细信息。现在我需要分割这个字符串,如果超过有限的长度假设100.直到现在它很容易。我可以使用以下方法拆分: -

 public static IEnumerable<string> SplitByLength(this string str, int maxLength)
 {
        for (int index = 0; index < str.Length; index += maxLength)
        {
            yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
        }
  }

But the thing is, this method just simply splits the string if it finds length is greater that 100. but I need to be sure if it tries to split from middle of the xml node, then it should find the just above <ProductDetails> node and split from there. what should I add to the code to achieve this?

但事实是,这个方法只是简单地拆分字符串,如果它发现长度大于100.但我需要确定它是否尝试从xml节点的中间分割,然后它应该找到正好在 节点之上并从那里分裂。我应该在代码中添加什么来实现这一目标?

2 个解决方案

#1


2  

You definitely should use XDocument instead of string to construct and query XML data.

你绝对应该使用XDocument而不是string来构造和查询XML数据。

You could create an extension method on XDocument class that will split by length:

您可以在XDocument类上创建一个将按长度拆分的扩展方法:

public static class XDocumentExtensions
{
    public static IEnumerable<string> SplitByLength(this XDocument source, string elementName, int maxLength)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (string.IsNullOrEmpty(elementName))
            throw new ArgumentException("elementName cannot be null or empty.", "elementName");
        if (maxLength <= 0)
            throw new ArgumentException("maxLength has to be greater than 0.", "maxLength");

        return SplitByLengthImpl(source, elementName, maxLength);
    }

    private static IEnumerable<string> SplitByLengthImpl(XDocument source, string elementName, int maxLength)
    {
        var builder = new StringBuilder();

        foreach (var element in source.Root.Elements(elementName))
        {
            var currentElementString = element.ToString();
            if (builder.Length + currentElementString.Length > maxLength)
            {
                if (builder.Length > 0)
                {
                    yield return builder.ToString();
                    builder.Clear();
                }
                else
                {
                    throw new ArgumentException(
                        "source document contains element with length greater than maxLength", "source");
                }
            }

            builder.AppendLine(currentElementString);
        }
        if (builder.Length > 0)
            yield return builder.ToString();
    }
}

And then use it like that:

然后像这样使用它:

var parts = doc.SplitByLength("ProductDetails", 200).ToList();

#2


3  

How about if lblproductid.Text contains, for ex, &, < or >?

如果lblproductid.Text包含,对于ex,&, <或> 怎么样?

Therefore I would use a real xml parser instead of forming it by hand.

因此我会使用真正的xml解析器而不是手工形成它。

var xElem = new XElement("Root",
                    new XElement("ProductDetails",
                        new XElement("PId", lblproductid.Text),
                        new XElement("PDesc",strtxtProductDesc)));

var xml = xElem.ToString();

output would be:

输出将是:

<Root>
  <ProductDetails>
    <PId>aaa</PId>
    <PDesc>aaa</PDesc>
  </ProductDetails>
</Root>

PS: You can loop for ProductDetails and count the total length.

PS:您可以循环使用ProductDetails并计算总长度。

#1


2  

You definitely should use XDocument instead of string to construct and query XML data.

你绝对应该使用XDocument而不是string来构造和查询XML数据。

You could create an extension method on XDocument class that will split by length:

您可以在XDocument类上创建一个将按长度拆分的扩展方法:

public static class XDocumentExtensions
{
    public static IEnumerable<string> SplitByLength(this XDocument source, string elementName, int maxLength)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (string.IsNullOrEmpty(elementName))
            throw new ArgumentException("elementName cannot be null or empty.", "elementName");
        if (maxLength <= 0)
            throw new ArgumentException("maxLength has to be greater than 0.", "maxLength");

        return SplitByLengthImpl(source, elementName, maxLength);
    }

    private static IEnumerable<string> SplitByLengthImpl(XDocument source, string elementName, int maxLength)
    {
        var builder = new StringBuilder();

        foreach (var element in source.Root.Elements(elementName))
        {
            var currentElementString = element.ToString();
            if (builder.Length + currentElementString.Length > maxLength)
            {
                if (builder.Length > 0)
                {
                    yield return builder.ToString();
                    builder.Clear();
                }
                else
                {
                    throw new ArgumentException(
                        "source document contains element with length greater than maxLength", "source");
                }
            }

            builder.AppendLine(currentElementString);
        }
        if (builder.Length > 0)
            yield return builder.ToString();
    }
}

And then use it like that:

然后像这样使用它:

var parts = doc.SplitByLength("ProductDetails", 200).ToList();

#2


3  

How about if lblproductid.Text contains, for ex, &, < or >?

如果lblproductid.Text包含,对于ex,&, <或> 怎么样?

Therefore I would use a real xml parser instead of forming it by hand.

因此我会使用真正的xml解析器而不是手工形成它。

var xElem = new XElement("Root",
                    new XElement("ProductDetails",
                        new XElement("PId", lblproductid.Text),
                        new XElement("PDesc",strtxtProductDesc)));

var xml = xElem.ToString();

output would be:

输出将是:

<Root>
  <ProductDetails>
    <PId>aaa</PId>
    <PDesc>aaa</PDesc>
  </ProductDetails>
</Root>

PS: You can loop for ProductDetails and count the total length.

PS:您可以循环使用ProductDetails并计算总长度。