簡體   English   中英

將字符串值分配給 InnerText XML 屬性值

[英]Assign string value to InnerText XML attribute value

我正在嘗試將字符串中的第一個單詞提取到firstName元素中。 所有剩余的單詞應該 go 在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"

請讓我知道為什么我會收到錯誤。

其他答案是正確的; 你有兩個問題:

  1. 您正在重用XmlElementfirstName標識符和從string.Split()方法返回的字符串數組。
  2. 您正在嘗試將字符串數組分配給XmlElement.innerText屬性,但它需要一個字符串。

要解決這些問題,請重命名或內聯變量之一,並更改您分配給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));

當您將var替換為顯式類型時,您可以看到firstNamestring ... 並且 String 沒有innerText屬性,但提供的代碼看起來不完整,因為如果該塊都在一個方法中,您應該會收到錯誤,因為雙重實例化。

因為,'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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM