[英]Assign string value to InnerText XML attribute value
我正在嘗試將字符串中的第一個單詞提取到firstName
元素中。 所有剩余的單詞應該 go 在lastName
元素中。
例子
ClientName = Stev Finance Company
這里Stev
是firstName
, Finance Company
是lastName
。
這是我的代碼,其中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"
請讓我知道為什么我會收到錯誤。
其他答案是正確的; 你有兩個問題:
XmlElement
的firstName
標識符和從string.Split()
方法返回的字符串數組。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
替換為顯式類型時,您可以看到firstName
是string
... 並且 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.