Why is tempspace here?

if we assumed that "AB" is a value for an xml element called given names, the following code converts that value to "A.tempspacetempspaceB". instead of "AB"

foreach (XElement initial in doc.XPathSelectElements("//given-names")) { string v = initial.Value.Replace(".", ". ").TrimEnd(' '); initial.SetValue(v); } 

So why does tempspace come here instead of literal space?

+4
source share
3 answers

First of all, the space is illegal inside the XML tag name, and if you are in a DOM or DOM object (which you :-) it is going to fight you until it disappears when you try to break the basic XML grammar - you can even call the cops if you insert: - )). I am surprised that he did not just throw at you when you tried. It simply cannot allow you to do this because it will no longer be XML.

Check out NMTOKEN .

+1
source

Your code gave me the expected results when I tested it. I order a try, I put together a little test in a console application. I used the following XML:

 <?xml version="1.0" encoding="utf-8" ?> <root> <user> <given-names>AB</given-names> </user> <user> <given-names>YZ</given-names> </user> </root> 

Then I created a new console application project and dropped this in the program class:

 class Program { static void Main(string[] args) { XDocument doc = XDocument.Load("XMLFile1.xml"); foreach (XElement initial in doc.XPathSelectElements("//given-names")) { string v = initial.Value.Replace(".", ". ").TrimEnd(' '); initial.SetValue(v); } Console.WriteLine(doc.ToString()); } } 

He produced the desired result:

 <root> <user> <given-names>AB</given-names> </user> <user> <given-names>YZ</given-names> </user> </root> 

There must be something else causing the problem. What environment do you work in? How do you convert an XDocument to a string for output?

+1
source

Have you tried decomposing method calls to find out if this works?

eg:.

 string v = initial.Value.Replace(".", ". "); v = v.TrimEnd(@"\s+"); initial.SetValue(v); 

Also did you check if your text encodings match? The XML analysis encoding is likely to be Unicode, while the default encoding for C # is US-ASCII. I'm not sure if this will make a difference, but it might be worth checking out.

0
source

Source: https://habr.com/ru/post/1309517/


All Articles