Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

C# -merge XML files but retain everything from the two files including version number

Suppose I have two XML files.

First XML File:

<?xml version="1.0"?>
    <AccessRequest xml:lang="en-US">
        <AccessLicenseNumber>Your_License</AccessLicenseNumber>
        <UserId>Your_ID</UserId>
        <Password>Your_Password</Password>
    </AccessRequest>

Second XML File:

   <?xml version="1.0"?>
    <RatingServiceSelectionRequest xml:lang="en-US">
     <CustomerContext>Rating and Service</CustomerContext>
    </RatingServiceSelectionRequest>

Now, when I merge them two, i want the output like this:

<?xml version="1.0"?>
<AccessRequest xml:lang="en-US">
    <AccessLicenseNumber>Your_License</AccessLicenseNumber>
    <UserId>Your_ID</UserId>
    <Password>Your_Password</Password>
</AccessRequest>
<?xml version="1.0"?>
<RatingServiceSelectionRequest xml:lang="en-US">
  <CustomerContext>Rating and Service</CustomerContext>
</RatingServiceSelectionRequest>

When I am merging these two files using the usual methods found on google, the version number etc are being eaten up and RatingServiceSelectionRequest node ends up being part of AccessRequest node, which is clearly not what I want.

How do I approach this in C#.Net?

Note: The reason I want it like that is because this API I'm using is requesting it like that, so no two ways about it I guess.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot have two top-level nodes

<AccessRequest>

and

<RatingServiceSelectionRequest>

in a well-formed XML file - that's by definition - a well-formed XML file has one and exactly one root node.

Also, you cannot have two XML processing instructions <?xml version="1.0"?> in a single file - most certainly not one in the middle of the file.

So you'll need to either introduce a new, "artificial" root, or stick on XML under the other root element or something.

If you really must keep that format, then you just concatenate the two files as strings:

string file1Contents = File.ReadAllText(@"file1.xml");
string file2Contents = File.ReadAllText(@"file2.xml");

File.WriteAllText(@"merged.xml", file1Contents + file2Contents);

No XML magic here ....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...