gpt4 book ai didi

xml - 写入和读取 xml 字符串的正确方法

转载 作者:数据小太阳 更新时间:2023-10-29 02:50:51 26 4
gpt4 key购买 nike

我已经在这堵墙上撞了很长一段时间了,所以我想我应该请教一些专家。

我需要从一台计算机向另一台计算机发送 xml 字符串。我想像这样格式化 xml:

<xml>
<author>Joe the Magnificent</author>
<title>Joe Goes Home</title>
</xml>

谁能提供一些帮助?

编辑:更多细节

我同时控制发送和接收,并成功地单向传输了一个硬编码字符串。

这是接收端:

    Dim author As String
Dim title As String

Dim xDoc As New XmlDocument
Dim xAuthor As XmlElement
Dim xTitle As XmlElement

xDoc.LoadXml(xml)
xAuthor = xDoc.FirstChild.Item("author")
xTitle = xDoc.FirstChild.Item("title")

author = xAuthor.FirstChild.Value
title = xTitle.FirstChild.Value

ShowMessage(author, title)

对于我来说,这主要是学习如何处理 XML 的练习,因此除了我自己的知识之外没有任何实际目的。我正在寻找一些关于做这些事情的最佳方式的意见。

最佳答案

使用 XmlDocument.Load方法,您有 4 个选项:来自 Stream、TextReader、URL 或 XmlReader。

您可以使用 NetworkStream类通过网络。您可以将 XML 发布到网站上,然后通过 URL 选项将其提取下来。您可能希望更具体地说明您希望在其中进行传输的协议(protocol)。

例如,要写入流,请使用流的 XmlWriter.Create 重载。使用 XmlWriterSettings 对象提供缩进。

   Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = true
settings.IndentChars = (ControlChars.Tab)
settings.OmitXmlDeclaration = true

Dim myNetworkStream As New NetworkStream(mySocket) 'mySocket is a whole other code sample

' Create the XmlWriter object and write some content.
writer = XmlWriter.Create(myNetworkStream, settings)
XmlDocument.WriteTo(writer)

[旧方法] 构造 xml 文档非常麻烦,我建议查看 VB9 XML 文字。然而,这里有一个 .NET 2 风格的 XmlDocument 操作示例:

    Dim doc As New XmlDocument()
Dim root As XmlElement = doc.CreateElement("xml")
Dim author As XmlElement = doc.CreateElement("author")
author.Value = "Joe the magnificent"
Dim title As XmlElement = doc.CreateElement("title")
title.Value = "Joe goes home"

root.AppendChild(author)
root.AppendChild(title)
doc.AppendChild(root)

关于xml - 写入和读取 xml 字符串的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/264249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com