开发者

why tempspace results here?

if we supposed that "A.B." is a value for an xml element called given-n开发者_JAVA技巧ames the following code converts this value to "A.tempspacetempspaceB." instead of "A. B."

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

So why tempspace comes here instead of literal space??


First of all space is illegal inside XML tag name and if you are in DOM or DOM-related object (which you are :-) he's going to fight you to extinction any time you try to break core XML grammar - may even call cops if you insit :-)). I'm surprised it didn't just throw at you when you tried. It just can't let you do it since it wouldn't be XML anymore.

Check out NMTOKEN definition.


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

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <user>
        <given-names>A.B.</given-names>
    </user>
    <user>
        <given-names>Y.Z.</given-names>
    </user>
</root>

Then I created a fresh console application project and threw 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());
    }
}

It produced the desired output:

<root>
    <user>
        <given-names>A. B.</given-names>
    </user>
    <user>
        <given-names>Y. Z.</given-names>
    </user>
</root>

There must be something else causing the problem here. What sort of environment are you working in? How are you converting the XDocument to a string for output?


Have you tried decomposing your method calls to see if that works?

e.g.:

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

Also, have you checked that your text encodings match? The encoding of the XML you're parsing is likely to be Unicode, whereas the default encoding for a string in C# is US-ASCII. I'm not sure if that will make a difference, but it might be worth checking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜