一个简单方法:构造xml的document,并将其转换为string

本文介绍如何使用Java创建XML文档并将其转换为字符串形式。包括Document对象的创建、添加节点及属性,以及利用Transformer进行文档到字符串的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    首先,构造一个document对象

	Document doc = null;
	try {
            doc = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder().newDocument();
	} catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
	}
    然后,在doc中加入需要的节点,例如:
	Element register = doc.createElement("Register");
	register.setAttribute("id", REGISTER_ATTRIB_ID);
	register.setAttribute("type", REGISTER_ATTRIB_TYPE);
	doc.appendChild(register);
		
	Element params = doc.createElement("Params");
	register.appendChild(params);

        Element item = doc.createElement(tagName);
        item.appendChild(doc.createTextNode(textNode));
        params.appendChild(item);
    最后,将document对象转换成字符串
	public static String convertDocToString(Document doc, String propertyName, String progertyValue){
		Transformer transformer = null;
		try {
			transformer = TransformerFactory.newInstance().newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
			return null;
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
			return null;
		}
		transformer.setOutputProperty(propertyName, progertyValue);
		DOMSource domSource = new DOMSource(doc);
		StreamResult streamResult = new StreamResult();
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		streamResult.setOutputStream(os);
		try {
			transformer.transform(domSource, streamResult);
		} catch (TransformerException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				os.flush();
				os.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return os.toString();
	}







帮我把以下代码转换成QT的格式,然后生成最新的头文件和源文件发给我#include <string> #include <vector> #include <unordered_map> #include <tinyxml2.h> // 确保安装 tinyxml2 库 class ProjectManager { public: // 构造函数和析构函数 ProjectManager(); ~ProjectManager(); // 加载项目文件 bool Load(const std::string& filePath); // 保存项目文件 bool Save(const std::string& projectFilePath); // 新建项目 bool NewProject(const std::string& projectFilePath); // 打开项目 bool OpenProject(const std::string& projectFilePath); // 另存为项目 bool SaveAsProject(const std::string& newFilePath); bool closeProject(); bool UpgradeProject(); // 获取项目信息 const std::string& GetProjectName() const; double GetCreatedAt() const; double GetModifiedAt() const; const std::string& GetControllerParamsFile() const; const std::string& GetCardParamsFile() const; const std::vector<std::string>& GetBasicCodeFiles() const; const std::vector<std::string>& GetGCodeFiles() const; const std::unordered_map<std::string, std::string>& GetAdditionalParams() const; // 设置项目信息 void SetProjectName(const std::string& name); void SetControllerParamsFile(const std::string& filePath); void SetCardParamsFile(const std::string& filePath); void AddBasicCodeFile(const std::string& filePath); void AddGCodeFile(const std::string& filePath); void SetAdditionalParam(const std::string& key, const std::string& value); private: // 项目信息 struct ProjectInfo { std::string version; std::string projectName; double createdAt; double modifiedAt; std::string controllerParamsFile; std::string cardParamsFile; std::vector<std::string> basicCodeFiles; std::vector<std::string> gCodeFiles; std::unordered_map<std::string, std::string> additionalParams; std::string projectFilePath; // 项目的完整路径 }; struct AxisInfo { int axisId; std::string axisName; std::string motorType; double gearRatio; double maxSpeed; double acceleration; }; // 私有成员 ProjectInfo projectInfo_; static const double CurrentVersion; // 静态成员变量声明 // 辅助方法 bool LoadControllerParams(const std::string& filePath); bool SaveControllerParams(const std::string& filePath); bool LoadCardParams(const std::string& filePath); bool SaveCardParams(const std::string& filePath); void HandleControllerBackwardsCompatibility(); void HandleCardBackwardsCompatibility(); void HandleBackwardsCompatibility(); void AddElement(tinyxml2::XMLElement* parent, const std::string& name, const std::string& value); }; #include "ProjectManager.h" #include <chrono> #include <ctime> #include <iostream> #include <sstream> // 包含字符串流处理头文件 // 当前软件版本 const double ProjectManager::CurrentVersion = 2.0; // 辅助函数:获取当前时间格式化为字符串 double GetCurrentTime() { std::time_t now = std::time(nullptr); return static_cast<double>(now); } // 构造函数和析构函数 ProjectManager::ProjectManager() { // 初始化默认值 projectInfo_.version = "1.0"; projectInfo_.projectName = "New Project"; projectInfo_.createdAt = GetCurrentTime(); projectInfo_.modifiedAt = projectInfo_.createdAt; projectInfo_.controllerParamsFile = "controller_params.xml"; projectInfo_.cardParamsFile = "card_params.xml"; projectInfo_.projectFilePath = ""; } ProjectManager::~ProjectManager() {} // 加载项目文件 bool ProjectManager::Load(const std::string& filePath) { tinyxml2::XMLDocument doc; if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_SUCCESS) { return false; } tinyxml2::XMLElement* root = doc.FirstChildElement("Project"); // 解析版本号 if (auto versionElem = root->FirstChildElement("Version")) { projectInfo_.version = versionElem->GetText(); } // 解析项目名称 if (auto nameElem = root->FirstChildElement("ProjectName")) { projectInfo_.projectName = nameElem->GetText(); } // 解析时间信息 if (auto createdAtElem = root->FirstChildElement("CreatedAt")) { projectInfo_.createdAt = std::stod(createdAtElem->GetText()); } if (auto modifiedAtElem = root->FirstChildElement("ModifiedAt")) { projectInfo_.modifiedAt = std::stod(modifiedAtElem->GetText()); } // 解析文件路径 if (auto controllerParamsElem = root->FirstChildElement("ControllerParamsFile")) { projectInfo_.controllerParamsFile = controllerParamsElem->GetText(); } if (auto cardParamsElem = root->FirstChildElement("CardParamsFile")) { projectInfo_.cardParamsFile = cardParamsElem->GetText(); } // 解析 Basic 代码文件路径 projectInfo_.basicCodeFiles.clear(); if (auto basicFilesElem = root->FirstChildElement("BasicCodeFiles")) { for (auto fileElem = basicFilesElem->FirstChildElement("File"); fileElem != nullptr; fileElem = fileElem->NextSiblingElement("File")) { projectInfo_.basicCodeFiles.push_back(fileElem->GetText()); } } // 解析 G 代码文件路径 projectInfo_.gCodeFiles.clear(); if (auto gcodeFilesElem = root->FirstChildElement("GCodeFiles")) { for (auto fileElem = gcodeFilesElem->FirstChildElement("File"); fileElem != nullptr; fileElem = fileElem->NextSiblingElement("File")) { projectInfo_.gCodeFiles.push_back(fileElem->GetText()); } } // 解析附加参数 projectInfo_.additionalParams.clear(); if (auto additionalParamsElem = root->FirstChildElement("AdditionalParams")) { for (auto paramElem = additionalParamsElem->FirstChildElement(); paramElem != nullptr; paramElem = paramElem->NextSiblingElement()) { projectInfo_.additionalParams[paramElem->Name()] = paramElem->GetText(); } } // 加载相关文件 if (!LoadControllerParams(projectInfo_.controllerParamsFile)) { return false; } if (!LoadCardParams(projectInfo_.cardParamsFile)) { return false; } // 设置项目文件路径 projectInfo_.projectFilePath = filePath; return true; } bool ProjectManager::Save(const std::string& projectFilePath) { // 先执行文件拷贝操作 const std::filesystem::path projectDir = std::filesystem::path(projectFilePath).parent_path(); // 拷贝运动控制器参数文件 if (!CopyPhysicalFile( currentControllerPath_, // 当前控制器参数文件路径(成员变量) projectDir / projectInfo_.controllerParamsFile)) { return false; } // 拷贝运动控制卡参数文件 if (!CopyPhysicalFile( currentCardPath_, // 当前控制卡参数文件路径(成员变量) projectDir / projectInfo_.cardParamsFile)) { return false; } //拷贝Basic代码文件 for (const auto& file : projectInfo_.basicCodeFiles) { if (!CopyPhysicalFile( currentBasicCodePath_ / file, // 当前Basic代码文件路径(成员变量) projectDir / file)) { return false; } } // 拷贝G代码文件 for (const auto& file : projectInfo_.gCodeFiles) { if (!CopyPhysicalFile( currentGCodePath_ / file, // 当前G代码文件路径(成员变量) projectDir / file)) { return false; } } // 构造 XML 文档 tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("Project"); doc.InsertEndChild(root); // 添加版本号 AddElement(root, "Version", std::to_string(CurrentVersion)); // 设置当前软件版本 // 添加项目名称 AddElement(root, "ProjectName", projectInfo_.projectName); // 添加创建时间和修改时间 AddElement(root, "CreatedAt", std::to_string(projectInfo_.createdAt)); AddElement(root, "ModifiedAt", std::to_string(GetCurrentTime())); // 更新修改时间 // 添加控制器参数文件路径 AddElement(root, "ControllerParamsFile", projectInfo_.controllerParamsFile); // 添加控制卡参数文件路径 AddElement(root, "CardParamsFile", projectInfo_.cardParamsFile); // 添加 Basic 代码文件路径 tinyxml2::XMLElement* basicCodeFiles = doc.NewElement("BasicCodeFiles"); root->InsertEndChild(basicCodeFiles); for (const auto& file : projectInfo_.basicCodeFiles) { AddElement(basicCodeFiles, "File", file); } // 添加 G 代码文件路径 tinyxml2::XMLElement* gCodeFiles = doc.NewElement("GCodeFiles"); root->InsertEndChild(gCodeFiles); for (const auto& file : projectInfo_.gCodeFiles) { AddElement(gCodeFiles, "File", file); } // 添加附加参数 tinyxml2::XMLElement* additionalParams = doc.NewElement("AdditionalParams"); root->InsertEndChild(additionalParams); for (const auto& param : projectInfo_.additionalParams) { AddElement(additionalParams, param.first, param.second); } // 保存文件 return doc.SaveFile(projectFilePath.c_str()) == tinyxml2::XML_SUCCESS; } bool ProjectManager::OpenProject(const std::string& projectFilePath) { if (!Load(projectFilePath)) { return false; } // 加载项目文件成功后,打印一些基本信息 std::cout << "Project Name: " << projectInfo_.projectName << std::endl; std::cout << "Controller Params File: " << projectInfo_.controllerParamsFile << std::endl; std::cout << "Card Params File: " << projectInfo_.cardParamsFile << std::endl; // 检查版本兼容性 double fileVersion = std::stod(projectInfo_.version); if (fileVersion > CurrentVersion) { std::cerr << "Error: Project version (" << projectInfo_.version << ") is newer than software version (" << CurrentVersion << "). Please upgrade your software." << std::endl; return false; } else if (fileVersion < CurrentVersion) { std::cout << "Warning: Project version (" << projectInfo_.version << ") is older than software version (" << CurrentVersion << "). Would you like to upgrade the project? (y/n): "; char choice; std::cin >> choice; if (choice == 'y' || choice == 'Y') { if (!UpgradeProject()) { std::cerr << "Failed to upgrade project." << std::endl; return false; } } else { return false; } } return true; } bool ProjectManager::UpgradeProject() { // 升级完成后,调用向下兼容性处理 HandleControllerBackwardsCompatibility(); HandleCardBackwardsCompatibility(); HandleCardBackwardsCompatibility(); // 保存升级后的项目文件 if (!Save(projectInfo_.projectFilePath)) { std::cerr << "Failed to save upgraded project." << std::endl; return false; } // 更新项目版本号 projectInfo_.version = std::to_string(currentVersion); std::cout << "Project upgraded successfully to version " << currentVersion << "." << std::endl; return true; } bool ProjectManager::NewProject(const std::string& projectFilePath) { // 初始化项目信息 projectInfo_.version = "1.0"; projectInfo_.projectName = "New Project"; projectInfo_.createdAt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); projectInfo_.modifiedAt = projectInfo_.createdAt; // 初始化控制器参数 projectInfo_.controllerParamsFile = "controller_params.xml"; if (!SaveControllerParams(projectInfo_.controllerParamsFile)) { return false; } // 初始化控制卡参数 projectInfo_.cardParamsFile = "card_params.xml"; if (!SaveCardParams(projectInfo_.cardParamsFile)) { return false; } // 保存项目文件 return Save(projectFilePath); } bool ProjectManager::SaveProject() { // 更新修改时间 projectInfo_.modifiedAt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // 保存控制器参数文件 if (!SaveControllerParams(projectInfo_.controllerParamsFile)) { return false; } // 保存控制卡参数文件 if (!SaveCardParams(projectInfo_.cardParamsFile)) { return false; } // 保存核心项目文件 return Save(projectInfo_.projectFilePath); } bool ProjectManager::SaveAsProject(const std::string& newFilePath) { // 更新项目文件路径 projectInfo_.projectFilePath = newFilePath; // 保存项目文件 return Save(projectFilePath); } bool ProjectManager::LoadControllerParams(const std::string& filePath) { tinyxml2::XMLDocument doc; if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_NO_ERROR) { return false; } tinyxml2::XMLElement* root = doc.FirstChildElement("ControllerParams"); // 解析控制器类型 projectInfo_.controllerType = root->FirstChildElement("ControllerType")->GetText(); // 解析轴数量 int axisCount = std::stoi(root->FirstChildElement("AxisCount")->GetText()); // 解析轴详细信息 projectInfo_.axisInfo.clear(); for (tinyxml2::XMLElement* axisNode = root->FirstChildElement("Axis"); axisNode; axisNode = axisNode->NextSiblingElement("Axis")) { AxisInfo axis; axis.axisId = std::stoi(axisNode->FirstChildElement("AxisId")->GetText()); axis.axisName = axisNode->FirstChildElement("AxisName")->GetText(); axis.motorType = axisNode->FirstChildElement("MotorType")->GetText(); axis.gearRatio = std::stod(axisNode->FirstChildElement("GearRatio")->GetText()); axis.maxSpeed = std::stod(axisNode->FirstChildElement("MaxSpeed")->GetText()); axis.acceleration = std::stod(axisNode->FirstChildElement("Acceleration")->GetText()); projectInfo_.axisInfo.push_back(axis); } return true; } bool ProjectManager::LoadCardParams(const std::string& filePath) { tinyxml2::XMLDocument doc; if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_NO_ERROR) { return false; } tinyxml2::XMLElement* root = doc.FirstChildElement("CardParams"); // 解析控制卡类型 projectInfo_.cardType = root->FirstChildElement("CardType")->GetText(); // 解析其他参数 projectInfo_.cardParams.clear(); for (auto elem = root->FirstChildElement(); elem; elem = elem->NextSiblingElement()) { if (elem->Name() == "CardType") continue; projectInfo_.cardParams[elem->Name()] = elem->GetText(); } return true; } bool ProjectManager::SaveControllerParams(const std::string& filePath) { tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("ControllerParams"); doc.InsertEndChild(root); // 添加控制器类型 AddElement(root, "ControllerType", projectInfo_.controllerType); // 添加轴数量 AddElement(root, "AxisCount", std::to_string(projectInfo_.axisInfo.size())); // 添加轴详细信息 for (const auto& axis : projectInfo_.axisInfo) { tinyxml2::XMLElement* axisNode = doc.NewElement("Axis"); root->InsertEndChild(axisNode); AddElement(axisNode, "AxisId", std::to_string(axis.axisId)); AddElement(axisNode, "AxisName", axis.axisName); AddElement(axisNode, "MotorType", axis.motorType); AddElement(axisNode, "GearRatio", std::to_string(axis.gearRatio)); AddElement(axisNode, "MaxSpeed", std::to_string(axis.maxSpeed)); AddElement(axisNode, "Acceleration", std::to_string(axis.acceleration)); } // 保存文件 return doc.SaveFile(filePath.c_str()) == tinyxml2::XML_NO_ERROR; } bool ProjectManager::SaveCardParams(const std::string& filePath) { tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("CardParams"); doc.InsertEndChild(root); // 添加控制卡类型 AddElement(root, "CardType", projectInfo_.cardType); // 添加其他参数 for (const auto& param : projectInfo_.cardParams) { AddElement(root, param.first, param.second); } // 保存文件 return doc.SaveFile(filePath.c_str()) == tinyxml2::XML_NO_ERROR; } void ProjectManager::HandleControllerBackwardsCompatibility() { double version = std::stod(projectInfo_.version); if (version == 1.0) { // 处理 v1.0 文件的缺失参数 // 例如,为新增的参数添加默认值 for (auto& axis : projectInfo_.axisInfo) { if (axis.acceleration == 0) { axis.acceleration = 500.0; // 默认值 } } } } void ProjectManager::HandleCardBackwardsCompatibility() { double version = std::stod(projectInfo_.version); if (version == 1.0) { // 处理 v1.0 文件的缺失参数 // 例如,为新增的参数添加默认值 if (projectInfo_.cardParams.find("NewParam1") == projectInfo_.cardParams.end()) { projectInfo_.cardParams["NewParam1"] = "DefaultValue1"; } } } void ProjectManager::HandleBackwardsCompatibility() { double version = std::stod(projectInfo_.version); if (version == 1.0) { // 处理 v1.0 文件的缺失参数 if (projectInfo_.additionalParams.find("NewParam1") == projectInfo_.additionalParams.end()) { projectInfo_.additionalParams["NewParam1"] = "DefaultValue1"; } } } void ProjectManager::AddElement(tinyxml2::XMLElement* parent, const std::string& name, const std::string& value) { // 获取父元素所属的XML文档对象 tinyxml2::XMLDocument* doc = parent->GetDocument(); // 创建新的子元素 tinyxml2::XMLElement* child = doc->NewElement(name.c_str()); // 设置子元素的文本内容 child->SetText(value.c_str()); // 将子元素添加到父元素中 parent->InsertEndChild(child); } bool ProjectManager::closeProject() { // 关闭项目时,先保存项目文件 //先提醒是否有未保存的修改 if (projectInfo_.modifiedAt != std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())) { std::cout << "Do you want to save the project before closing? (y/n): "; char choice; std::cin >> choice; if (choice == 'y' || choice == 'Y') { if (!SaveProject()) { return false; } } } return true; }
最新发布
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值