先将xml文件加载到XmlDocument对象中,然后再加载到String对象中,这样就可以将一个xml文件转换字符串的形式了。如果只是调用XmlDocument()方法,只会返回类型名称。
先将xml文件加载到XmlDocument对象中,然后再加载到String对象中,这样就可以将一个xml文件转换字符串的形式了。如果只是调用XmlDocument()方法,只会返回类型名称。
01
//convert xml file into a String object in boo
02
import System
03
import System.Xml
04
import System.IO
05
06
def xmldoc2str(filePath):
07
doc = XmlDocument()
08
try:
09
doc.Load(filePath)
10
except FileNotFoundException:
11
print "File Not Found!"
12
sw = StringWriter()
13
xw = XmlTextWriter(sw)
14
doc.WriteTo(xw)
15
print sw.ToString()

02

03

04

05

06

07

08

09

10

11

12

13

14

15

01
// convert xml file into a string object in c#
02
string xmldoc2str(string filePath)
03
{
04
XmlDocument xmlDoc = new XmlDocument();
05
try
06
{
07
xmlDoc.Load(filePath);
08
}
09
catch (FileNotFoundException e)
10
{
11
throw;
12
}
13
StringWriter sw = new StringWriter();
14
XmlTextWriter xw = new XmlTextWriter(sw);
15
xmlDoc.WriteTo(xw);
16
return sw.ToString();
17
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

也可以动态创建一个XmlDocument对象,然后通过上面的方法转换为String对象。
文中用到的xml文件demo.xml
1 <item>
2 <name>wrench</name>
3 </item>
2 <name>wrench</name>
3 </item>