【问题标题】:Assign string value to InnerText XML attribute value将字符串值分配给 InnerText XML 属性值
【发布时间】:2021-04-23 00:18:24
【问题描述】:

我正在尝试将字符串中的第一个单词提取到firstName 元素中。所有剩余的单词都应该放在lastName 元素中。

示例

ClientName = Stev Finance Company

这里StevfirstNameFinance CompanylastName

这是我的代码,其中doc 是一个 XML 文档:

// XML construction – no issue here 
XmlDocument Mainroot = new XmlDocument();
XmlElement root = Mainroot.CreateElement("Parent");
XmlElement firstName = Mainroot.CreateElement("FirstName");
XmlElement lastName = Mainroot.CreateElement("LastName");

var clientname = XmlHelper.getString(doc, "//BusinessClient/ClientName"); 
var firstName = clientname.Split(' ');
var lastName = clientname.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);

firstName.InnerText = firstName; // Getting an error: "Cannot Convert string[] to string"
lastName.InnerText = lastName; // Getting an error: "Cannot Convert string[] to string"

请告诉我为什么会出错。

【问题讨论】:

    标签: c# asp.net .net xml


    【解决方案1】:

    其他答案都是正确的;你有两个问题:

    1. 您将 firstName 标识符重用于 XmlElement 和从 string.Split() 方法返回的字符串数组。
    2. 您正在尝试将字符串数组分配给XmlElement.innerText 属性,但它需要一个字符串。

    要解决这些问题,请重命名或内联变量之一,并将您分配给string 的值的类型更改为string[] 而不是string[]。您可以通过使用string.Join() 将字符串数组中的值连接回字符串来实现此目的。在下面的示例中,值用空格连接,第一个单词被跳过(因为它被用作名字)。

    // XML construction – no issue here 
    XmlDocument Mainroot = new XmlDocument();
    XmlElement root = Mainroot.CreateElement("Parent");
    XmlElement firstName = Mainroot.CreateElement("FirstName");
    XmlElement lastName = Mainroot.CreateElement("LastName");
    
    var clientname = XmlHelper.getString(doc, "//BusinessClient/ClientName"); 
    
    // Set the value of this element to the first word in the client name.
    firstName.innerText = clientname.Split(' ').FirstOrDefault();
    
    // Set the value of this element to the rest of the word(s) in the client name.
    lastName.innerText = string.Join(" ", clientname.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries).Skip(1));
    

    【讨论】:

    • 感谢您的回复,这里又是 FirstOrDefault();并且未找到 Skip(1) - 这是我遇到的错误
    • FirstOrDefault()Skip()Linq 库中可用。通过在文件顶部包含 using System.Linq; 将它们添加到您的项目中。
    【解决方案2】:

    因为,'Split' 方法返回字符串数组。如果你只想得到一个字符串,试试这个: var firstName = clientname.Split(' ').FirstOrDefault(); var lastName = clientname.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

    https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-5.0

    【讨论】:

    【解决方案3】:

    当您用显式类型替换 var 时,您可以看到 firstNamestring... 并且 String 没有 innerText 属性,但提供的代码看起来不完整,因为您应该得到如果该块由于双重实例化而全部在一个方法中,则会出错。

    【讨论】:

    • 请告诉我如何实现这一点,我需要从 ClientName 中提取 FirstName 和 last,然后我需要重新插入新的 XML 标签
    • 那么你应该阅读 XmlDocument 的文档:docs.microsoft.com/de-de/dotnet/api/… where are here for HELP,不做你的工作;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多